import SwiftData
import SwiftUI

struct DMConversationView: View {
    let partnerId: String
    let partnerName: String
    @Environment(ConnectionManager.self) private var manager
    @Query private var messages: [SavedMessage]
    @State private var messageText = ""

    init(partnerId: String, partnerName: String) {
        self.partnerId = partnerId
        self.partnerName = partnerName

        let pid = partnerId
        _messages = Query(
            filter: #Predicate<SavedMessage> {
                $0.buffer == "direct-messages" && $0.characterId == pid
            },
            sort: \.timestamp
        )
    }

    var body: some View {
        VStack(spacing: 0) {
            ScrollViewReader { proxy in
                ScrollView {
                    LazyVStack(alignment: .leading, spacing: 8) {
                        ForEach(messages) { message in
                            MessageRow(message: message)
                                .id(message.persistentModelID)
                        }
                    }
                    .padding()
                }
                .onChange(of: messages.count) {
                    if let last = messages.last {
                        proxy.scrollTo(last.persistentModelID, anchor: .bottom)
                    }
                }
            }

            HStack(spacing: 8) {
                TextField("Message \(partnerName)...", text: $messageText, axis: .vertical)
                    .textFieldStyle(.roundedBorder)
                    .lineLimit(1...4)
                    .onSubmit { sendMessage() }

                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)
        }
        .navigationTitle(partnerName)
        .navigationBarTitleDisplayMode(.inline)
    }

    private func sendMessage() {
        let text = messageText.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !text.isEmpty else { return }
        manager.sendDirectMessage(recipientId: partnerId, message: text)
        messageText = ""
    }
}
