import SwiftUI

struct ChatBufferView: View {
    let bufferName: String
    let canSend: Bool
    var onDM: ((ChatMessage) -> Void)?
    @Environment(ConnectionManager.self) private var manager
    @State private var messageText = ""

    private var messages: [ChatMessage] {
        manager.messages[bufferName] ?? []
    }

    var body: some View {
        VStack(spacing: 0) {
            ScrollViewReader { proxy in
                ScrollView {
                    LazyVStack(alignment: .leading, spacing: 12) {
                        ForEach(messages) { message in
                            MessageRow(
                                message: message,
                                onDM: onDM
                            )
                            .id(message.id)
                        }
                    }
                    .padding()
                }
                .onChange(of: messages.count) {
                    if let lastId = messages.last?.id {
                        withAnimation(.easeOut(duration: 0.2)) {
                            proxy.scrollTo(lastId, anchor: .bottom)
                        }
                    }
                }
            }

            if canSend {
                HStack(spacing: 8) {
                    TextField("Message...", text: $messageText, axis: .vertical)
                        .textFieldStyle(.roundedBorder)
                        .lineLimit(1...4)
                        .onSubmit { sendMessage() }
                        .toolbar {
                            ToolbarItemGroup(placement: .keyboard) {
                                Button("/command", systemImage: "slash.circle") {
                                    if !messageText.hasPrefix("/") {
                                        messageText = "/" + messageText
                                    }
                                }
                                .labelStyle(.titleAndIcon)
                                Spacer()
                            }
                        }

                    Button("Send", systemImage: "arrow.up.circle.fill", action: sendMessage)
                        .labelStyle(.iconOnly)
                        .font(.title)
                        .buttonStyle(.borderedProminent)
                        .buttonBorderShape(.circle)
                        .disabled(messageText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
                }
                .padding(.horizontal)
                .padding(.vertical, 8)
                .background(.bar)
            }
        }
    }

    private func sendMessage() {
        let text = messageText.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !text.isEmpty else { return }

        manager.sendChatMessage(buffer: bufferName, content: text)
        messageText = ""
    }

}
