import SwiftUI
import SharedModels
import SwiftData
import PencilKit

struct HandwritingView: View {
    @Environment(\.modelContext) private var modelContext
    @Environment(\.cloudModelContextProvider) private var cloudModelContextProvider
    var viewModel: PracticeViewModel
    let speechService: SpeechService

    @State private var drawing = PKDrawing()
    @State private var recognizedText = ""
    @State private var isRecognizing = false

    private var cloudModelContext: ModelContext { cloudModelContextProvider() }

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

                if viewModel.isAnswerRevealed {
                    // Result
                    VStack(spacing: 12) {
                        if viewModel.isCorrect == true {
                            Image(systemName: "checkmark.circle.fill")
                                .font(.system(size: 44))
                                .foregroundStyle(.green)
                            Text("Correct!")
                                .font(.title3.bold())
                                .foregroundStyle(.green)
                        } else {
                            Image(systemName: "xmark.circle.fill")
                                .font(.system(size: 44))
                                .foregroundStyle(.red)

                            if !recognizedText.isEmpty {
                                Text("Recognized: \"\(recognizedText)\"")
                                    .font(.subheadline)
                                    .foregroundStyle(.secondary)
                            }
                        }
                    }
                    .transition(.blurReplace)

                    // Answer review + navigation
                    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
                            )
                            resetCanvas()
                        },
                        onNext: {
                            viewModel.loadNextCard(
                                localContext: modelContext,
                                cloudContext: cloudModelContext
                            )
                            resetCanvas()
                        }
                    )
                    .transition(.move(edge: .bottom).combined(with: .opacity))
                } else {
                    // Canvas
                    VStack(spacing: 12) {
                        Text("Write the conjugation")
                            .font(.subheadline)
                            .foregroundStyle(.secondary)

                        HandwritingCanvas(drawing: $drawing)
                            .frame(height: 200)
                            .background(.fill.quinary, in: RoundedRectangle(cornerRadius: 16))
                            .overlay(
                                RoundedRectangle(cornerRadius: 16)
                                    .stroke(.separator, lineWidth: 1)
                            )

                        // Recognized text preview
                        if !recognizedText.isEmpty {
                            Text("Recognized: \"\(recognizedText)\"")
                                .font(.caption)
                                .foregroundStyle(.secondary)
                                .transition(.opacity)
                        }

                        HStack(spacing: 16) {
                            Button {
                                resetCanvas()
                            } label: {
                                Label("Clear", systemImage: "trash")
                                    .font(.subheadline)
                            }
                            .tint(.secondary)

                            Button {
                                checkHandwriting()
                            } label: {
                                HStack {
                                    if isRecognizing {
                                        ProgressView()
                                            .tint(.white)
                                    }
                                    Text("Check")
                                        .font(.headline)
                                }
                                .frame(maxWidth: .infinity)
                                .padding(.vertical, 12)
                            }
                            .buttonStyle(.borderedProminent)
                            .disabled(drawing.strokes.isEmpty || isRecognizing)
                        }
                    }
                    .padding(.horizontal)
                }
            }
            .padding()
            .adaptiveContainer()
        }
        .animation(.smooth, value: viewModel.isAnswerRevealed)
    }

    private func checkHandwriting() {
        isRecognizing = true
        Task {
            let result = await HandwritingRecognizer.recognize(drawing: drawing)
            await MainActor.run {
                recognizedText = result.text
                isRecognizing = false

                let correct = viewModel.currentForm?.form ?? ""
                let isMatch = HandwritingRecognizer.checkAnswer(result: result, expected: correct)
                viewModel.isCorrect = isMatch
                viewModel.isAnswerRevealed = true
                if isMatch {
                    viewModel.sessionCorrect += 1
                }
                viewModel.sessionTotal += 1
            }
        }
    }

    private func resetCanvas() {
        drawing = PKDrawing()
        recognizedText = ""
    }
}

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