import SwiftUI
import SharedModels
import SwiftData

/// Study session containing only cards the user has marked for extra study,
/// scoped to a specific (courseName, weekNumber). Resolves marks by re-hashing
/// each VocabCard via `CourseCardStore.reviewKey` so the matching is robust to
/// duplicate (deckId, front, back) tuples that differ in examples.
struct ExtraStudyView: View {
    let courseName: String
    let weekNumber: Int

    @Environment(\.modelContext) private var localContext
    @Environment(\.cloudModelContextProvider) private var cloudModelContextProvider
    @Environment(\.dismiss) private var dismiss

    @State private var cards: [VocabCard] = []
    @State private var speechService = SpeechService()
    @State private var loaded = false

    private var cloudContext: ModelContext { cloudModelContextProvider() }

    var body: some View {
        Group {
            if !loaded {
                ProgressView()
                    .controlSize(.large)
            } else if cards.isEmpty {
                ContentUnavailableView(
                    "No Marked Cards",
                    systemImage: "star",
                    description: Text("Tap the star on a card during study to add it here.")
                )
            } else {
                VocabFlashcardView(
                    cards: cards.shuffled(),
                    speechService: speechService,
                    onDone: {
                        ReviewStore.recordActivity(context: cloudContext)
                        dismiss()
                    },
                    deckTitle: "Extra Study",
                    markContext: ExtraStudyMarkContext(
                        courseName: courseName,
                        weekNumber: weekNumber
                    )
                )
            }
        }
        .navigationTitle("Extra Study · Week \(weekNumber)")
        .navigationBarTitleDisplayMode(.inline)
        .task { load() }
    }

    private func load() {
        guard !loaded else { return }
        let marks = ExtraStudyStore(context: cloudContext)
            .fetch(courseName: courseName, weekNumber: weekNumber)
        let markIds = Set(marks.map(\.id))
        let deckIds = Set(marks.map(\.deckId))

        var collected: [VocabCard] = []
        for deckId in deckIds {
            let descriptor = FetchDescriptor<VocabCard>(
                predicate: #Predicate<VocabCard> { $0.deckId == deckId }
            )
            let deckCards = (try? localContext.fetch(descriptor)) ?? []
            collected.append(contentsOf: deckCards.filter {
                markIds.contains(CourseCardStore.reviewKey(for: $0))
            })
        }
        cards = collected
        loaded = true
    }
}
