import SwiftUI
import ApplicationServices

@MainActor
class AppState: ObservableObject {
    static let shared = AppState()
    
    @Published var isRecordingGlobally = false
    @Published var restoreClipboard = true // Restore clipboard after pasting
    @Published var showInDock = false // Show app icon in Dock (default: hidden)
    
    let mediaKeyMonitor = MediaKeyMonitor()
    let recognizer = ParakeetSpeechRecognizer()
    
    private var targetTextElement: AXUIElement?
    
    private init() {
        setupMediaKeyMonitor()
        loadPreferences()
    }
    
    private func setupMediaKeyMonitor() {
        mediaKeyMonitor.onMicrophoneButtonPress = { [weak self] in
            Task { @MainActor in
                await self?.handleDictationKeyPress()
            }
        }
    }
    
    private func loadPreferences() {
        restoreClipboard = UserDefaults.standard.object(forKey: "restoreClipboard") as? Bool ?? true
        showInDock = UserDefaults.standard.object(forKey: "showInDock") as? Bool ?? false
        
        print("📋 Loaded preferences: clipboardRestore=\(restoreClipboard), showInDock=\(showInDock)")
        
        // Apply dock visibility
        applyDockVisibility()
        
        // Always start dictation key monitor
        mediaKeyMonitor.start()
    }
    
    func toggleClipboardRestore() {
        restoreClipboard.toggle()
        UserDefaults.standard.set(restoreClipboard, forKey: "restoreClipboard")
        print("♻️  Clipboard restore: \(restoreClipboard ? "ON" : "OFF")")
    }
    
    func toggleDockIcon() {
        showInDock.toggle()
        UserDefaults.standard.set(showInDock, forKey: "showInDock")
        applyDockVisibility()
        print("🖥️  Dock icon: \(showInDock ? "VISIBLE" : "HIDDEN")")
    }
    
    private func applyDockVisibility() {
        if showInDock {
            NSApp.setActivationPolicy(.regular)
        } else {
            NSApp.setActivationPolicy(.accessory)
        }
    }
    
    private func handleDictationKeyPress() async {
        // Toggle recording when dictation key is pressed
        if recognizer.isRecording {
            // Stop recording
            await stopGlobalRecording()
        } else {
            // Start recording
            let (_, element) = AccessibilityHelper.isTextFieldFocused()
            targetTextElement = element
            print("🎤 Dictation key pressed - starting recording")
            await startGlobalRecording()
        }
    }
    
    private func startGlobalRecording() async {
        isRecordingGlobally = true
        
        // Clear previous transcript for global mode
        recognizer.clearTranscript()
        
        // Start recording (app is called "lowercase" - default to lowercase!)
        await recognizer.startRecording(lowercase: true)
    }
    
    private func stopGlobalRecording() async {
        await recognizer.stopRecording()
        isRecordingGlobally = false
        
        // Save and paste the transcribed text
        if !recognizer.transcript.isEmpty {
            print("📋 Preparing to paste transcription: \"\(recognizer.transcript)\"")
            
            // Save current clipboard
            let savedClipboard = NSPasteboard.general.string(forType: .string)
            print("💾 Saved original clipboard")
            
            // Copy transcription to clipboard
            NSPasteboard.general.clearContents()
            NSPasteboard.general.setString(recognizer.transcript, forType: .string)
            print("📋 Copied transcript to clipboard")
            
            // Longer delay to ensure clipboard is ready and app is ready to receive paste
            try? await Task.sleep(nanoseconds: 200_000_000) // 200ms
            
            // Always use Command+V paste for now (more reliable than accessibility insert)
            print("🎯 Attempting Command+V paste...")
            let didPaste = AccessibilityHelper.pasteText()
            
            // Give paste time to complete
            try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
            
            if didPaste {
                print("✅ Paste completed successfully")
            } else {
                print("⚠️  Paste failed - text is still in clipboard for manual paste")
            }
            
            // Restore original clipboard after a delay (if enabled)
            if restoreClipboard {
                Task {
                    try? await Task.sleep(nanoseconds: 500_000_000) // 500ms
                    if let saved = savedClipboard {
                        NSPasteboard.general.clearContents()
                        NSPasteboard.general.setString(saved, forType: .string)
                        print("♻️  Original clipboard restored")
                    }
                }
            } else {
                print("⏭️  Clipboard restore disabled - transcription stays in clipboard")
            }
            
            // Clear transcript for next recording
            recognizer.clearTranscript()
        }
        
        targetTextElement = nil
    }
}





