import SwiftUI
import SharedModels
import SwiftData

struct MultipleChoiceView: View {
    @Environment(\.modelContext) private var modelContext
    @Environment(\.cloudModelContextProvider) private var cloudModelContextProvider
    var viewModel: PracticeViewModel
    let speechService: SpeechService
    @State private var selectedIndex: Int?

    private var cloudModelContext: ModelContext { cloudModelContextProvider() }

    var body: some View {
        ScrollView {
            VStack(spacing: 24) {
                PracticeHeaderView(
                    verb: viewModel.currentVerb,
                    tenseInfo: viewModel.currentTenseInfo,
                    person: viewModel.currentPerson
                )

                // Choice buttons
                VStack(spacing: 12) {
                    ForEach(Array(viewModel.multipleChoiceOptions.enumerated()), id: \.offset) { index, option in
                        ChoiceButton(
                            text: option,
                            state: choiceState(for: index, option: option),
                            action: {
                                guard !viewModel.isAnswerRevealed else { return }
                                selectedIndex = index
                                withAnimation(.smooth) {
                                    _ = viewModel.checkAnswer(option)
                                }
                            }
                        )
                    }
                }
                .padding(.horizontal)

                // Answer review
                if viewModel.isAnswerRevealed {
                    AnswerReviewView(
                        form: viewModel.currentForm,
                        spans: viewModel.currentSpans,
                        speechService: speechService,
                        onRate: { quality in
                            viewModel.rateAnswer(
                                quality: quality,
                                localContext: modelContext,
                                cloudContext: cloudModelContext
                            )
                            selectedIndex = nil
                            viewModel.loadNextCard(
                                localContext: modelContext,
                                cloudContext: cloudModelContext
                            )
                        },
                        onNext: {
                            selectedIndex = nil
                            viewModel.loadNextCard(
                                localContext: modelContext,
                                cloudContext: cloudModelContext
                            )
                        }
                    )
                    .transition(.move(edge: .bottom).combined(with: .opacity))
                }
            }
            .padding()
            .adaptiveContainer()
        }
        .animation(.smooth, value: viewModel.isAnswerRevealed)
    }

    private func choiceState(for index: Int, option: String) -> ChoiceButton.ButtonState {
        guard viewModel.isAnswerRevealed else { return .idle }
        let correctForm = viewModel.currentForm?.form ?? ""
        if option == correctForm {
            return .correct
        } else if index == selectedIndex {
            return .incorrect
        }
        return .dimmed
    }
}

private struct ChoiceButton: View {
    let text: String
    let state: ButtonState
    let action: () -> Void

    enum ButtonState {
        case idle, correct, incorrect, dimmed
    }

    private var tintColor: Color {
        switch state {
        case .idle: .primary
        case .correct: .green
        case .incorrect: .red
        case .dimmed: .secondary
        }
    }

    private var symbolName: String? {
        switch state {
        case .correct: "checkmark.circle.fill"
        case .incorrect: "xmark.circle.fill"
        default: nil
        }
    }

    var body: some View {
        Button(action: action) {
            HStack {
                Text(text)
                    .font(.title3.weight(.medium))
                Spacer()
                if let symbolName {
                    Image(systemName: symbolName)
                        .font(.title3)
                        .foregroundStyle(tintColor)
                        .transition(.scale.combined(with: .opacity))
                }
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(.horizontal, 20)
            .padding(.vertical, 16)
        }
        .tint(tintColor)
        .glassEffect(in: RoundedRectangle(cornerRadius: 16))
        .opacity(state == .dimmed ? 0.5 : 1.0)
        .disabled(state != .idle)
    }
}

#Preview {
    NavigationStack {
        MultipleChoiceView(viewModel: PracticeViewModel(), speechService: SpeechService())
    }
    .modelContainer(for: Verb.self, inMemory: true)
}
