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 = ""
    @FocusState private var isInputFocused: Bool

    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: isInputFocused) { _, focused in
                    if focused, let last = messages.last {
                        proxy.scrollTo(last.persistentModelID, anchor: .bottom)
                    }
                }
                .onChange(of: messages.count) {
                    guard let last = messages.last, last.sessionId == manager.sessionId else { return }
                    Task { @MainActor in
                        proxy.scrollTo(last.persistentModelID, anchor: .bottom)
                    }

                    // Sound
                    if UserDefaults.standard.bool(forKey: "sounds_enabled", default: true),
                       UserDefaults.standard.bool(forKey: "sounds_dm", default: true) {
                        SoundPlayer.play("direct-message")
                    }

                    // VoiceOver announcement
                    if !last.isSystem {
                        AccessibilityNotification.Announcement(
                            "\(last.senderName): \(last.content)"
                        ).post()
                    }

                    // Haptic
                    if UserDefaults.standard.bool(forKey: "haptics_enabled", default: true),
                       UserDefaults.standard.bool(forKey: "haptics_messages", default: true) {
                        UIImpactFeedbackGenerator(style: .soft).impactOccurred()
                    }
                }
            }

            HStack(spacing: 8) {
                TextField("Message \(partnerName)...", text: $messageText, axis: .vertical)
                    .focused($isInputFocused)
                    .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 = ""
        isInputFocused = true
    }
}
