import SwiftUI
import SharedModels
import SwiftData

struct SettingsView: View {
    @Environment(\.cloudModelContextProvider) private var cloudModelContextProvider
    @State private var progress: UserProgress?

    @State private var dailyGoal: Double = 50
    @State private var showVosotros: Bool = true
    @State private var autoFillStem: Bool = false
    @State private var selectedLevel: VerbLevel = .basic

    private let levels = VerbLevel.allCases
    private var cloudModelContext: ModelContext { cloudModelContextProvider() }

    var body: some View {
        NavigationStack {
            Form {
                Section("Practice") {
                    VStack(alignment: .leading) {
                        Text("Daily Goal: \(Int(dailyGoal)) cards")
                        Slider(value: $dailyGoal, in: 10...200, step: 10)
                    }
                    .onChange(of: dailyGoal) { _, newValue in
                        progress?.dailyGoal = Int(newValue)
                        saveProgress()
                    }

                    Toggle("Include vosotros", isOn: $showVosotros)
                        .onChange(of: showVosotros) { _, newValue in
                            progress?.showVosotros = newValue
                            saveProgress()
                        }

                    Toggle("Auto-fill verb stem (Full Table)", isOn: $autoFillStem)
                        .onChange(of: autoFillStem) { _, newValue in
                            progress?.autoFillStem = newValue
                            saveProgress()
                        }
                }

                Section("Level") {
                    Picker("Current Level", selection: $selectedLevel) {
                        ForEach(levels, id: \.self) { level in
                            Text(level.displayName).tag(level)
                        }
                    }
                    .onChange(of: selectedLevel) { _, newValue in
                        progress?.selectedVerbLevel = newValue
                        saveProgress()
                    }
                }

                Section("Tenses") {
                    ForEach(TenseInfo.all) { tense in
                        Toggle(tense.english, isOn: Binding(
                            get: {
                                progress?.enabledTenseIDs.contains(tense.id) ?? false
                            },
                            set: { enabled in
                                guard let progress else { return }
                                progress.setTenseEnabled(tense.id, enabled: enabled)
                                saveProgress()
                            }
                        ))
                    }
                }

                Section("Stats") {
                    if let progress {
                        LabeledContent("Total Reviewed", value: "\(progress.totalReviewed)")
                        LabeledContent("Current Streak", value: "\(progress.currentStreak) days")
                        LabeledContent("Longest Streak", value: "\(progress.longestStreak) days")
                    }
                }

                Section("About") {
                    LabeledContent("Version", value: "1.0.0")
                }
            }
            .navigationTitle("Settings")
            .onAppear(perform: loadProgress)
        }
    }

    private func loadProgress() {
        let resolved = ReviewStore.fetchOrCreateUserProgress(context: cloudModelContext)
        progress = resolved
        dailyGoal = Double(resolved.dailyGoal)
        showVosotros = resolved.showVosotros
        autoFillStem = resolved.autoFillStem
        selectedLevel = resolved.selectedVerbLevel
    }

    private func saveProgress() {
        try? cloudModelContext.save()
    }
}

#Preview {
    SettingsView()
        .modelContainer(for: UserProgress.self, inMemory: true)
}
