import SwiftUI
import MultipeerConnectivity
import Combine

struct ChatView: View {
    @EnvironmentObject var multipeerSession: MultipeerSession
    @StateObject var speechRecognizer = SpeechRecognizer()
    @ObservedObject var networkMonitor = NetworkMonitor.shared
    
    let userName: String
    let userRole: UserRole
    let userColorHex: String
    
    @AppStorage("isOnboardingComplete") var isOnboardingComplete: Bool = true
    @State private var messageText: String = ""
    @State private var waitingDots = 0
    let timer = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
    
    var body: some View {
        ZStack {
            // 1. Animated Mesh Background
            MeshBackground(colors: [
                Color(hex: userColorHex),
                userRole == .deaf ? .purple : .cyan,
                .black
            ])
            
            VStack(spacing: 0) {
                // 2. Floating Dynamic Header
                HStack {
                    Button(action: {
                        speechRecognizer.stopRecording()
                        multipeerSession.stop()
                        isOnboardingComplete = false
                    }) {
                        HStack(spacing: 6) {
                            Image(systemName: "chevron.left")
                            Text("Leave")
                        }
                        .font(.system(.subheadline, design: .rounded, weight: .bold))
                        .foregroundColor(.white)
                        .padding(.horizontal, 16)
                        .padding(.vertical, 8)
                        .background(.ultraThinMaterial)
                        .cornerRadius(20)
                    }
                    
                    Spacer()
                    
                    VStack(spacing: 2) {
                        Text("MESH")
                            .font(.system(size: 10, weight: .black, design: .monospaced))
                            .tracking(2)
                            .foregroundColor(.white.opacity(0.6))
                        
                        Text("\(multipeerSession.connectedPeers.count) Active")
                            .font(.caption2)
                            .fontWeight(.bold)
                            .foregroundColor(.green)
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 6)
                    .background(.ultraThinMaterial)
                    .cornerRadius(20)
                }
                .padding(.horizontal)
                .padding(.top, 50) // Safe Area
                .padding(.bottom, 10)
                
                // 3. Peer Status / Live Transcriptions
                if multipeerSession.connectedPeers.isEmpty {
                    VStack {
                        Spacer()
                        
                        // Show "Warming up..." on first connection when not on WiFi
                        if !networkMonitor.isWiFi {
                            Text("Warming up" + String(repeating: ".", count: waitingDots))
                                .font(.title3)
                                .fontWeight(.medium)
                                .foregroundColor(.white.opacity(0.7))
                                .onReceive(timer) { _ in
                                    waitingDots = (waitingDots + 1) % 4
                                }
                            
                            Text("No WiFi: connection may take up to 60 seconds")
                                .font(.caption)
                                .foregroundColor(.orange)
                                .padding(.top, 8)
                        } else {
                            Text("Searching for others" + String(repeating: ".", count: waitingDots))
                                .font(.title3)
                                .fontWeight(.medium)
                                .foregroundColor(.white.opacity(0.7))
                                .onReceive(timer) { _ in
                                    waitingDots = (waitingDots + 1) % 4
                                }
                        }
                        
                        Spacer()
                    }
                } else {
                    // Connected Peers Row (Small Pills)
                    if !multipeerSession.connectedPeerUsers.isEmpty {
                        HStack(spacing: 8) {
                            ScrollView(.horizontal, showsIndicators: false) {
                                HStack(spacing: 12) {
                                    ForEach(multipeerSession.connectedPeerUsers, id: \.self) { peer in
                                        HStack(spacing: 6) {
                                            Circle()
                                                .fill(Color(hex: peer.colorHex))
                                                .frame(width: 8, height: 8)
                                            Text(peer.name)
                                                .font(.caption)
                                                .fontWeight(.bold)
                                                .foregroundColor(.white)
                                        }
                                        .padding(.horizontal, 10)
                                        .padding(.vertical, 6)
                                        .background(.ultraThinMaterial)
                                        .cornerRadius(12)
                                    }
                                }
                                .padding(.leading)
                            }
                            
                            // Full Mesh Indicator
                            if multipeerSession.isAtCapacity {
                                Text("FULL")
                                    .font(.system(size: 10, weight: .black, design: .monospaced))
                                    .foregroundColor(.orange)
                                    .padding(.horizontal, 8)
                                    .padding(.vertical, 4)
                                    .background(Color.orange.opacity(0.2))
                                    .cornerRadius(8)
                                    .padding(.trailing)
                            }
                        }
                        .padding(.vertical, 8)
                    }
                    
                    // 4. Message List
                    ScrollViewReader { proxy in
                        ScrollView {
                            LazyVStack(spacing: 12) {
                                ForEach(multipeerSession.receivedMessages) { message in
                                    MessageBubble(
                                        message: message,
                                        isMyMessage: message.senderNodeID == multipeerSession.myNodeIDPublic
                                    )
                                    .id(message.id)
                                    .transition(.opacity.combined(with: .scale(scale: 0.95)))
                                }
                            }
                            .padding(.bottom, 20)
                        }
                        .scrollIndicators(.hidden)
                        .onChange(of: multipeerSession.receivedMessages.count) {
                            if let lastId = multipeerSession.receivedMessages.last?.id {
                                withAnimation {
                                    proxy.scrollTo(lastId, anchor: .bottom)
                                }
                            }
                            
                            if userRole == .deaf {
                                if let lastMsg = multipeerSession.receivedMessages.last, lastMsg.senderNodeID != multipeerSession.myNodeIDPublic {
                                    let generator = UINotificationFeedbackGenerator()
                                    generator.notificationOccurred(.success)
                                }
                            }
                        }
                        // Auto-scroll when transcription card appears to prevent blocking
                        .onChange(of: multipeerSession.liveTranscripts.isEmpty) {
                            if !multipeerSession.liveTranscripts.isEmpty {
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                                    if let lastId = multipeerSession.receivedMessages.last?.id {
                                        withAnimation {
                                            proxy.scrollTo(lastId, anchor: .bottom)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                // Live Transcription Cards (Moved to Bottom)
                // Live Transcription Cards (Moved to Bottom, Stacked Vertically)
                if userRole == .deaf && !multipeerSession.liveTranscripts.isEmpty {
                     VStack(spacing: 8) {
                         ForEach(multipeerSession.liveTranscripts.sorted(by: { $0.key < $1.key }), id: \.key) { nodeIDKey, text in
                            // Look up friendly name from connectedPeerUsers by nodeID
                            let displayName = multipeerSession.connectedPeerUsers.first(where: { $0.nodeID == nodeIDKey })?.name ?? nodeIDKey
                            VStack(alignment: .leading, spacing: 6) {
                                Text(displayName)
                                    .font(.caption2)
                                    .fontWeight(.bold)
                                    .foregroundColor(Color.cyan)
                                
                                ScrollViewReader { proxy in
                                    ScrollView {
                                        VStack(alignment: .leading) {
                                            Text(text)
                                                .font(.caption)
                                                .foregroundColor(.white)
                                                .shadow(color: .black, radius: 1)
                                                .multilineTextAlignment(.leading)
                                                .id("text-\(nodeIDKey)")
                                            
                                            Spacer(minLength: 0)
                                                .id("bottom-\(nodeIDKey)")
                                        }
                                    }
                                    .onChange(of: text) {
                                        withAnimation(.easeOut(duration: 0.1)) {
                                            proxy.scrollTo("bottom-\(nodeIDKey)", anchor: .bottom)
                                        }
                                    }
                                }
                            }
                            .padding(12)
                            .frame(maxWidth: .infinity)
                            .frame(height: 70) // Fixed height for approx 2 lines
                            .liquidCard()
                         }
                     }
                     .padding(.horizontal)
                     .padding(.bottom, 10)
                     .transition(.move(edge: .bottom).combined(with: .opacity))
                }
                
                // 5. Input Bar
                InputBar(
                    userRole: userRole,
                    text: $messageText,
                    isRecording: $speechRecognizer.isRecording,
                    transcript: speechRecognizer.transcript,
                    onSend: sendMessage,
                    onToggleRecording: toggleRecording
                )
            }
        }
        .ignoresSafeArea(.container, edges: .all)
        .onAppear {
            UIApplication.shared.isIdleTimerDisabled = true
            multipeerSession.start()
            
            // Re-apply identity if needed (though App state should handle it)
            if multipeerSession.userName != userName {
                multipeerSession.setIdentity(name: userName, colorHex: userColorHex, role: userRole)
            }
            
            // Configure Speech Recognizer callback
            speechRecognizer.onFinalResult = { resultText in
                let message = MeshMessage(
                    id: UUID(),
                    senderID: userName,
                    senderNodeID: multipeerSession.myNodeIDPublic,
                    senderInstance: multipeerSession.myInstancePublic,
                    senderRole: userRole,
                    senderColorHex: userColorHex,
                    content: resultText,
                    isTranscription: true,
                    isPartial: false,
                    timestamp: Date()
                )
                multipeerSession.send(message: message)
            }
            
            // Configure Partial Result callback (No Throttling)
            speechRecognizer.onPartialResult = { partialText in
                let message = MeshMessage(
                    id: UUID(),
                    senderID: userName,
                    senderNodeID: multipeerSession.myNodeIDPublic, // Added NodeID for consistent transcript keying
                    senderInstance: multipeerSession.myInstancePublic,
                    senderRole: userRole,
                    senderColorHex: userColorHex,
                    content: partialText,
                    isTranscription: true,
                    isPartial: true,
                    timestamp: Date()
                )
                multipeerSession.send(message: message)
            }
            
            // Auto-start recording for Hearing users
            if userRole == .hearing {
                speechRecognizer.startRecording()
            }
        }
        .onDisappear {
            UIApplication.shared.isIdleTimerDisabled = false
        }
    }
    
    func sendMessage() {
        guard !messageText.isEmpty else { return }
        
        let message = MeshMessage(
            id: UUID(),
            senderID: userName,
            senderNodeID: multipeerSession.myNodeIDPublic, // Added NodeID
            senderInstance: multipeerSession.myInstancePublic,
            senderRole: userRole,
            senderColorHex: userColorHex,
            content: messageText,
            isTranscription: false,
            isPartial: false,
            timestamp: Date()
        )
        
        multipeerSession.send(message: message)
        messageText = ""
    }
    
    func toggleRecording() {
        if speechRecognizer.isRecording {
            speechRecognizer.stopRecording()
        } else {
            speechRecognizer.startRecording()
        }
    }
}
