import SwiftUI
import AVFoundation
import AVKit
#if canImport(Translation)
import Translation
#endif

struct SettingsView: View {
    @EnvironmentObject var themeManager: ThemeManager
    @ObservedObject var voiceManager = VoiceManager.shared
    @State private var showRecommendedVoices = false
    @Environment(\.dismiss) var dismiss
    
    // Easter Egg State
    @State private var lightbulbTapCount = 0
    @State private var showEasterEgg = false
    
    // Persist selected language
    @AppStorage("targetLanguageIdentifier") private var targetLanguageIdentifier: String = ""
    
    // Download confirmation state
    @State private var showDownloadAlert = false
    @State private var languageToDownload: LanguageManager.LanguageStatus?
    @State private var previousLanguageIdentifier: String = ""
    
    // Translation configuration for triggering download
    #if canImport(Translation)
    @State private var downloadConfig: TranslationSession.Configuration?
    #endif
    
    var body: some View {
        NavigationStack {
            Form {
                Section(header: Text("Theme Colors")
                                    .font(.title2)
                                    .bold()
                                    .foregroundColor(.primary)
                                    .textCase(nil)) {
                    Picker("Theme Colors", selection: $themeManager.currentTheme) {
                        ForEach(AppTheme.allCases) { theme in
                            Text(theme.displayName)
                                .tag(theme)
                                .onTapGesture {
                                    themeManager.currentTheme = theme
                                    if theme == .lightbulb {
                                        lightbulbTapCount += 1
                                        if lightbulbTapCount >= 5 {
                                            showEasterEgg = true
                                            lightbulbTapCount = 0
                                        }
                                    } else {
                                        lightbulbTapCount = 0
                                    }
                                }
                        }
                    }
                    .pickerStyle(.inline)
                    .labelsHidden()
                }

                Section(header: Text("Translation Language")
                                    .font(.title2)
                                    .bold()
                                    .foregroundColor(.primary)
                                    .textCase(nil)) {
                    Picker("Target Language", selection: $targetLanguageIdentifier) {
                        Text("Select a language").tag("")
                        ForEach(LanguageManager.shared.supportedLanguages) { lang in
                            if lang.isDownloadAvailable {
                                Text("\(lang.flag) \(lang.name) (Download available)").tag(lang.id)
                            } else {
                                Text("\(lang.flag) \(lang.name) (Internet required)").tag(lang.id)
                            }
                        }
                    }
                    .pickerStyle(.navigationLink)
                }
                
                Section(header: Text("Voice Settings")
                                    .font(.title2)
                                    .bold()
                                    .foregroundColor(.primary)
                                    .textCase(nil),
                        footer: Text("Tip: For the most natural sound, download \"Enhanced\" or \"Premium\" voices in your iPhone Settings:\nSettings > Accessibility > Read & Speak > Voices.")
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                                    .padding(.top, 8)) {
                    
                    VStack(alignment: .leading) {
                        Text("English Voice")
                            .font(.headline)
                        Picker("English (US)", selection: $voiceManager.selectedEnglishVoiceIdentifier) {
                            ForEach(voiceManager.availableEnglishVoices, id: \.identifier) { voice in
                                Text(voiceManager.description(for: voice))
                                    .tag(voice.identifier)
                            }
                        }
                        .pickerStyle(.menu)
                    }
                    
                    VStack(alignment: .leading) {
                        // Dynamic Header for Target Voice
                        if let lang = LanguageManager.shared.supportedLanguages.first(where: { $0.id == targetLanguageIdentifier }) {
                            Text("\(lang.name) Voice")
                                .font(.headline)
                        } else {
                            Text("Target Language Voice")
                                .font(.headline)
                        }
                        
                        Picker("Voice", selection: $voiceManager.selectedTargetVoiceIdentifier) {
                            ForEach(voiceManager.availableTargetVoices, id: \.identifier) { voice in
                                Text(voiceManager.description(for: voice))
                                    .tag(voice.identifier)
                            }
                        }
                        .pickerStyle(.menu)
                        .disabled(voiceManager.availableTargetVoices.isEmpty)
                        
                        if voiceManager.availableTargetVoices.isEmpty {
                            Text("No specific voices found for this language. System default will be used.")
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                    }
                    
                    Button(action: {
                        showRecommendedVoices = true
                    }) {
                        Text("See recommended voices.")
                            .font(.subheadline)
                            .foregroundColor(.blue)
                    }
                }
            }
            .navigationTitle("Settings")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Close") {
                        dismiss()
                    }
                }
            }
            .onAppear {
                // Ensure VoiceManager has the correct target language loaded on appear
                if !targetLanguageIdentifier.isEmpty {
                    voiceManager.updateTargetLanguage(to: targetLanguageIdentifier)
                }
            }
            .onChange(of: targetLanguageIdentifier) { oldValue, newValue in
                // Update voice manager when user picks a new language
                voiceManager.updateTargetLanguage(to: newValue)
                
                // Check if this language is downloadable and prompt for download
                if !newValue.isEmpty,
                   let lang = LanguageManager.shared.supportedLanguages.first(where: { $0.id == newValue }),
                   lang.isDownloadAvailable {
                    previousLanguageIdentifier = oldValue
                    languageToDownload = lang
                    showDownloadAlert = true
                }
            }
            .onDisappear {
                // Settings closed
            }
            .alert("Download Language", isPresented: $showDownloadAlert) {
                Button("Download") {
                    triggerDownload()
                }
                Button("Not Now", role: .cancel) {
                    // Keep the selection but don't download
                    languageToDownload = nil
                }
            } message: {
                if let lang = languageToDownload {
                    Text("Would you like to download \(lang.name) for offline translation? This provides faster translations and works without internet.")
                } else {
                    Text("Would you like to download this language for offline translation?")
                }
            }
            #if canImport(Translation)
            .translationTask(downloadConfig) { session in
                // This will trigger Apple's download UI automatically
                do {
                    try await session.prepareTranslation()
                } catch {
                    print("Download preparation failed: \(error)")
                }
                await MainActor.run {
                    downloadConfig = nil
                    languageToDownload = nil
                }
            }
            #endif
            .sheet(isPresented: $showRecommendedVoices) {
                RecommendedVoicesView()
            }
            .fullScreenCover(isPresented: $showEasterEgg) {
                EasterEggPlayerView()
            }
        }
    }
    
    private func triggerDownload() {
        guard let lang = languageToDownload else { return }
        
        #if canImport(Translation)
        if #available(iOS 18.0, *) {
            // Create a configuration to trigger the download
            downloadConfig = TranslationSession.Configuration(
                source: Locale.Language(identifier: "en-US"),
                target: Locale.Language(identifier: lang.id)
            )
        }
        #endif
    }
}

struct EasterEggPlayerView: View {
    @Environment(\.dismiss) var dismiss
    @State private var player: AVPlayer?
    
    var body: some View {
        ZStack {
            Color.black.edgesIgnoringSafeArea(.all)
            
            if let player = player {
                VideoPlayer(player: player)
                    .edgesIgnoringSafeArea(.all)
                    .onAppear {
                        player.play()
                        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: .main) { _ in
                            dismiss()
                        }
                    }
            } else {
                ProgressView()
            }
        }
        .onAppear {
            if let url = Bundle.main.url(forResource: "easteregg", withExtension: "mp4") {
                self.player = AVPlayer(url: url)
            } else {
                print("Easter egg video not found")
                dismiss()
            }
        }
        .onDisappear {
            player?.pause()
            NotificationCenter.default.removeObserver(self)
        }
    }
}
