import SwiftUI
import AVFoundation
import UIKit

/// Voice + speed picker shown from the book reader's toolbar. Lists Spanish
/// voices currently installed on the device grouped by quality, and offers a
/// shortcut to the iOS Settings app where the user can download premium voices
/// (no public deep-link to the Accessibility section exists, so we open the
/// app's own Settings page with a hint).
struct BookVoicePickerSheet: View {
    @Binding var voiceIdentifier: String?
    @Binding var rate: Float
    @Environment(\.dismiss) private var dismiss

    private struct VoiceGroup: Identifiable {
        let id: String
        let title: String
        let voices: [AVSpeechSynthesisVoice]
    }

    private var groups: [VoiceGroup] {
        let all = AVSpeechSynthesisVoice.speechVoices()
            .filter { $0.language.hasPrefix("es") }
        let buckets: [(String, AVSpeechSynthesisVoiceQuality)] = [
            ("Premium", .premium),
            ("Enhanced", .enhanced),
            ("Default", .default),
        ]
        return buckets.compactMap { (title, quality) in
            let voices = all
                .filter { $0.quality == quality }
                .sorted { lhs, rhs in
                    if lhs.language != rhs.language { return lhs.language < rhs.language }
                    return lhs.name < rhs.name
                }
            return voices.isEmpty ? nil : VoiceGroup(id: title, title: title, voices: voices)
        }
    }

    var body: some View {
        NavigationStack {
            Form {
                Section("Speed") {
                    Picker("Speed", selection: $rate) {
                        Text("Slow").tag(Float(0.40))
                        Text("Normal").tag(Float(0.50))
                        Text("Fast").tag(Float(0.55))
                    }
                    .pickerStyle(.segmented)
                }

                if groups.isEmpty {
                    Section {
                        ContentUnavailableView(
                            "No Spanish voices",
                            systemImage: "person.wave.2",
                            description: Text("Install a Spanish voice in Settings → Accessibility → Spoken Content → Voices.")
                        )
                    }
                } else {
                    ForEach(groups) { group in
                        Section(group.title) {
                            ForEach(group.voices, id: \.identifier) { voice in
                                voiceRow(voice)
                            }
                        }
                    }
                }

                Section {
                    Button {
                        openSettings()
                    } label: {
                        Label("Download more voices…", systemImage: "arrow.down.circle")
                    }
                } footer: {
                    Text("Opens Settings. Navigate to Accessibility → Spoken Content → Voices → Spanish to install premium or enhanced voices.")
                }
            }
            .navigationTitle("Read aloud")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button("Done") { dismiss() }
                }
            }
        }
    }

    private func voiceRow(_ voice: AVSpeechSynthesisVoice) -> some View {
        Button {
            voiceIdentifier = voice.identifier
        } label: {
            HStack(spacing: 12) {
                VStack(alignment: .leading, spacing: 2) {
                    Text(voice.name)
                        .font(.body)
                        .foregroundStyle(.primary)
                    Text(voice.language)
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
                Spacer()
                if voice.identifier == voiceIdentifier {
                    Image(systemName: "checkmark")
                        .foregroundStyle(.indigo)
                }
            }
        }
        .tint(.primary)
    }

    private func openSettings() {
        if let url = URL(string: UIApplication.openSettingsURLString) {
            UIApplication.shared.open(url)
        }
    }
}
