import SwiftUI
import SwiftData
import SharedModels

struct VerbListView: View {
    @Environment(\.modelContext) private var modelContext
    @State private var verbs: [Verb] = []
    @State private var searchText = ""
    @State private var selectedLevel: String?
    @State private var selectedVerb: Verb?

    private var filteredVerbs: [Verb] {
        var result = verbs
        if let level = selectedLevel {
            result = result.filter { VerbLevelGroup.matches($0.level, selectedLevel: level) }
        }
        if !searchText.isEmpty {
            let query = searchText.lowercased()
            result = result.filter {
                $0.infinitive.lowercased().contains(query) ||
                $0.english.lowercased().contains(query)
            }
        }
        return result
    }

    private let levels = ["basic", "elementary", "intermediate", "advanced", "expert"]

    var body: some View {
        NavigationSplitView {
            List(filteredVerbs, selection: $selectedVerb) { verb in
                NavigationLink(value: verb) {
                    VerbRowView(verb: verb)
                }
            }
            .navigationTitle("Verbs")
            .searchable(text: $searchText, prompt: "Search verbs...")
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Menu {
                        Button("All Levels") { selectedLevel = nil }
                        ForEach(levels, id: \.self) { level in
                            Button(level.capitalized) { selectedLevel = level }
                        }
                    } label: {
                        Label("Filter", systemImage: "line.3.horizontal.decrease.circle")
                    }
                }
            }
            .task { loadVerbs() }
            .onAppear { loadVerbs() }
        } detail: {
            if let verb = selectedVerb {
                VerbDetailView(verb: verb)
            } else {
                ContentUnavailableView("Select a Verb", systemImage: "textformat.abc", description: Text("Choose a verb from the list to see its conjugations."))
            }
        }
    }

    private func loadVerbs() {
        // Hit the shared local container directly, bypassing @Environment.
        guard let container = SharedStore.localContainer else {
            print("[VerbListView] ⚠️ SharedStore.localContainer is nil")
            return
        }
        if let url = SharedStore.localStoreURL() {
            StoreInspector.dump(at: url, label: "verb-list-load")
        }
        let context = ModelContext(container)
        verbs = ReferenceStore(context: context).fetchVerbs()
        print("[VerbListView] loaded \(verbs.count) verbs (container: \(ObjectIdentifier(container)))")
    }
}

struct VerbRowView: View {
    let verb: Verb

    var body: some View {
        HStack {
            VStack(alignment: .leading, spacing: 2) {
                Text(verb.infinitive)
                    .font(.headline)
                Text(verb.english)
                    .font(.subheadline)
                    .foregroundStyle(.secondary)
            }

            Spacer()

            Text(verb.level.prefix(3).uppercased())
                .font(.caption2)
                .fontWeight(.semibold)
                .padding(.horizontal, 8)
                .padding(.vertical, 4)
                .background(levelColor(verb.level).opacity(0.15))
                .foregroundStyle(levelColor(verb.level))
                .clipShape(Capsule())
        }
    }

    private func levelColor(_ level: String) -> Color {
        switch level {
        case "basic": return .green
        case "elementary": return .blue
        case "intermediate": return .orange
        case "advanced": return .red
        case "expert": return .purple
        default: return .gray
        }
    }
}

#Preview {
    VerbListView()
        .modelContainer(for: Verb.self, inMemory: true)
}
