import SwiftUI
import SharedModels
import SwiftData

struct TypingView: View {
    @Environment(\.modelContext) private var modelContext
    @Environment(\.cloudModelContextProvider) private var cloudModelContextProvider
    @Bindable var viewModel: PracticeViewModel
    let speechService: SpeechService
    @FocusState private var isTextFieldFocused: Bool

    private var cloudModelContext: ModelContext { cloudModelContextProvider() }

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

                if viewModel.isAnswerRevealed {
                    // Result display
                    VStack(spacing: 16) {
                        if viewModel.isCorrect == true {
                            Image(systemName: "checkmark.circle.fill")
                                .font(.system(size: 48))
                                .foregroundStyle(.green)
                                .symbolEffect(.bounce, value: viewModel.isCorrect)

                            Text("Correct!")
                                .font(.title2.bold())
                                .foregroundStyle(.green)
                        } else {
                            Image(systemName: "xmark.circle.fill")
                                .font(.system(size: 48))
                                .foregroundStyle(.red)
                                .symbolEffect(.bounce, value: viewModel.isCorrect)

                            Text("Your answer: \(viewModel.userAnswer)")
                                .font(.subheadline)
                                .foregroundStyle(.secondary)
                                .strikethrough()
                        }
                    }
                    .transition(.blurReplace)
                } else {
                    // Input area
                    VStack(spacing: 16) {
                        TextField("Type the conjugation...", text: $viewModel.userAnswer)
                            .font(.title2)
                            .multilineTextAlignment(.center)
                            .textInputAutocapitalization(.never)
                            .autocorrectionDisabled()
                            .keyboardType(.default)
                            .focused($isTextFieldFocused)
                            .submitLabel(.done)
                            .onSubmit { submitAnswer() }
                            .padding()
                            .glassEffect(in: RoundedRectangle(cornerRadius: 16))

                        Button {
                            submitAnswer()
                        } label: {
                            Text("Check")
                                .font(.headline)
                                .frame(maxWidth: .infinity)
                                .padding(.vertical, 14)
                        }
                        .buttonStyle(.borderedProminent)
                        .disabled(viewModel.userAnswer.trimmingCharacters(in: .whitespaces).isEmpty)
                    }
                    .padding(.horizontal)
                    .transition(.blurReplace)
                }

                // 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
                            )
                            viewModel.loadNextCard(
                                localContext: modelContext,
                                cloudContext: cloudModelContext
                            )
                            isTextFieldFocused = true
                        },
                        onNext: {
                            viewModel.loadNextCard(
                                localContext: modelContext,
                                cloudContext: cloudModelContext
                            )
                            isTextFieldFocused = true
                        }
                    )
                    .transition(.move(edge: .bottom).combined(with: .opacity))
                }
            }
            .padding()
            .adaptiveContainer()
        }
        .animation(.smooth, value: viewModel.isAnswerRevealed)
        .onAppear { isTextFieldFocused = true }
        .onChange(of: viewModel.currentForm?.form) { isTextFieldFocused = true }
    }

    private func submitAnswer() {
        guard !viewModel.userAnswer.trimmingCharacters(in: .whitespaces).isEmpty else { return }
        withAnimation(.smooth) {
            _ = viewModel.checkAnswer(viewModel.userAnswer)
        }
    }
}

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