import SwiftUI
import SharedModels
import SwiftData

struct VerbDetailView: View {
    @Environment(\.modelContext) private var modelContext
    @State private var speechService = SpeechService()
    let verb: Verb
    @State private var selectedTense: TenseInfo = TenseInfo.all[0]

    private var formsForTense: [VerbForm] {
        ReferenceStore(context: modelContext).fetchForms(verbId: verb.id, tenseId: selectedTense.id)
    }

    var body: some View {
        List {
            Section {
                LabeledContent("English", value: verb.english)
                LabeledContent("Ending", value: "-\(verb.ending)")
                LabeledContent("Level", value: VerbLevel(rawValue: verb.level)?.displayName ?? verb.level.capitalized)
                if verb.reflexive > 0 {
                    LabeledContent("Reflexive", value: verb.reflexive == 2 ? "Always" : "Yes")
                }
            } header: {
                Text("Info")
            }

            Section {
                Picker("Tense", selection: $selectedTense) {
                    ForEach(TenseInfo.all) { tense in
                        Text(tense.english)
                            .tag(tense)
                    }
                }
                .pickerStyle(.menu)

                if formsForTense.isEmpty {
                    ContentUnavailableView("No forms loaded", systemImage: "exclamationmark.triangle")
                } else {
                    ForEach(formsForTense, id: \.personIndex) { form in
                        HStack {
                            Text(TenseInfo.persons[form.personIndex])
                                .foregroundStyle(.secondary)
                                .frame(minWidth: 100, alignment: .leading)
                            Text(form.form)
                                .fontWeight(form.regularity != "ordinary" ? .semibold : .regular)
                                .foregroundStyle(form.regularity != "ordinary" ? .red : .primary)
                        }
                    }
                }
            } header: {
                Text("Conjugation")
            }
        }
        .navigationTitle(verb.infinitive)
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button {
                    speechService.speak(verb.infinitive)
                } label: {
                    Image(systemName: "speaker.wave.2.fill")
                }
                .tint(.secondary)
            }
        }
    }
}

#Preview {
    NavigationStack {
        VerbDetailView(verb: Verb(id: 1, infinitive: "hablar", english: "to speak", rank: 1, ending: "ar", reflexive: 0, level: "basic"))
    }
    .modelContainer(for: [Verb.self, VerbForm.self], inMemory: true)
}
