import SwiftUI

// MARK: - PersonalityQuizView

/// Sheet-tauglicher Container für den vollständigen Quiz-Flow.
/// Zeigt: Intro → Fragen → Ergebnis.
/// Wenn `skipIntro = true`, wird der Intro-Screen übersprungen.
struct PersonalityQuizView: View {
    let onComplete: (PersonalityProfile?) -> Void
    var skipIntro: Bool = false

    @Environment(\.dismiss) private var dismiss

    private enum Phase: Equatable {
        case intro
        case genderSelection
        case questions
        case result(PersonalityProfile)

        static func == (lhs: Phase, rhs: Phase) -> Bool {
            switch (lhs, rhs) {
            case (.intro, .intro), (.genderSelection, .genderSelection), (.questions, .questions): return true
            case (.result, .result): return true
            default:                 return false
            }
        }
    }

    @State private var phase: Phase

    init(onComplete: @escaping (PersonalityProfile?) -> Void, skipIntro: Bool = false) {
        self.onComplete = onComplete
        self.skipIntro  = skipIntro
        let hasGender = !UserProfileStore.shared.gender.isEmpty
        self._phase = State(initialValue: skipIntro
            ? (hasGender ? .questions : .genderSelection)
            : .intro)
    }

    /// Nächste Phase nach dem Intro – überspringt Geschlechtsabfrage wenn bereits gesetzt.
    private func nextPhaseAfterIntro() -> Phase {
        UserProfileStore.shared.gender.isEmpty ? .genderSelection : .questions
    }

    var body: some View {
        Group {
            switch phase {
            case .intro:
                QuizIntroScreen(
                    onStart: { withAnimation(.spring(response: 0.4)) { phase = nextPhaseAfterIntro() } },
                    onSkip:  { onComplete(nil); dismiss() }
                )

            case .genderSelection:
                GenderSelectionScreen(
                    onContinue: { withAnimation(.spring(response: 0.4)) { phase = .questions } },
                    onSkip:     { onComplete(nil); dismiss() }
                )

            case .questions:
                QuizQuestionsScreen(
                    onComplete: { profile in
                        withAnimation(.spring(response: 0.4)) { phase = .result(profile) }
                    },
                    onSkip: { onComplete(nil); dismiss() }
                )

            case .result(let profile):
                PersonalityResultView(
                    profile:    profile,
                    onContinue: { onComplete(profile); dismiss() }
                )
            }
        }
    }
}

// MARK: - QuizIntroScreen

/// Warmer Einstiegsscreen. Kann direkt in OnboardingContainerView
/// und innerhalb von PersonalityQuizView eingesetzt werden.
struct QuizIntroScreen: View {
    let onStart: () -> Void
    let onSkip:  () -> Void

    var body: some View {
        VStack(spacing: 0) {
            Spacer()

            Image(systemName: "brain.head.profile")
                .font(.system(size: 72))
                .foregroundStyle(NahbarInsightStyle.accentPetrol)
                .accessibilityHidden(true)
                .padding(.bottom, 32)

            VStack(spacing: 12) {
                Text("Wie tickst du?")
                    .font(.title.bold())
                    .multilineTextAlignment(.center)

                Text("10 kurze Situationen. Keine falschen Antworten. Dauert etwa 2 Minuten.")
                    .font(.body)
                    .foregroundStyle(.secondary)
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, 32)
            }
            .padding(.bottom, 24)

            PrivacyBadgeView(context: .localOnly)
                .padding(.horizontal, NahbarInsightStyle.horizontalPadding)

            Spacer()

            VStack(spacing: 14) {
                Button(action: onStart) {
                    Text("Quiz starten")
                        .font(.headline)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 14)
                        .background(NahbarInsightStyle.accentPetrol)
                        .foregroundStyle(.white)
                        .clipShape(RoundedRectangle(cornerRadius: 12))
                }
                .accessibilityLabel("Persönlichkeitsquiz starten")

                Button(action: onSkip) {
                    Text("Überspringen")
                        .font(.subheadline.weight(.medium))
                        .foregroundStyle(.secondary)
                }
                .accessibilityLabel("Quiz überspringen")
            }
            .padding(.horizontal, NahbarInsightStyle.horizontalPadding)
            .padding(.bottom, 40)
        }
    }
}

// MARK: - GenderSelectionScreen

/// Kurze Geschlechtsabfrage vor den Quiz-Fragen.
/// Speichert die Auswahl sofort in UserProfileStore (single-purpose update).
private struct GenderSelectionScreen: View {
    let onContinue: () -> Void
    let onSkip:     () -> Void

    private let options = ["Männlich", "Weiblich", "Divers"]

    @State private var selected: String = UserProfileStore.shared.gender

    var body: some View {
        VStack(spacing: 0) {
            Spacer()

            Image(systemName: "person.fill")
                .font(.system(size: 60))
                .foregroundStyle(NahbarInsightStyle.accentPetrol)
                .accessibilityHidden(true)
                .padding(.bottom, 32)

            VStack(spacing: 10) {
                Text("Kurze Frage vorab")
                    .font(.title.bold())
                    .multilineTextAlignment(.center)

                Text("Dein Geschlecht hilft, die Auswertung besser einzuordnen.")
                    .font(.body)
                    .foregroundStyle(.secondary)
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, 32)
            }
            .padding(.bottom, 32)

            // Chip-Auswahl
            HStack(spacing: 12) {
                ForEach(options, id: \.self) { option in
                    let isSelected = selected == option
                    Button {
                        selected = isSelected ? "" : option
                    } label: {
                        Text(option)
                            .font(.subheadline.weight(.medium))
                            .padding(.horizontal, 20)
                            .padding(.vertical, 12)
                            .background(isSelected
                                        ? NahbarInsightStyle.recommendedTint
                                        : Color(.tertiarySystemBackground))
                            .foregroundStyle(isSelected
                                             ? NahbarInsightStyle.accentPetrol
                                             : .primary)
                            .clipShape(Capsule())
                            .overlay(Capsule().strokeBorder(
                                isSelected ? NahbarInsightStyle.accentPetrol : Color.secondary.opacity(0.2),
                                lineWidth: isSelected ? 2 : 1))
                    }
                    .buttonStyle(.plain)
                    .animation(.easeInOut(duration: 0.15), value: isSelected)
                    .accessibilityLabel(option)
                    .accessibilityAddTraits(isSelected ? .isSelected : [])
                }
            }
            .padding(.horizontal, NahbarInsightStyle.horizontalPadding)
            .padding(.bottom, 32)

            PrivacyBadgeView(context: .localOnly)
                .padding(.horizontal, NahbarInsightStyle.horizontalPadding)
                .padding(.bottom, 24)

            Spacer()

            VStack(spacing: 14) {
                Button(action: advance) {
                    Text("Weiter")
                        .font(.headline)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 14)
                        .background(NahbarInsightStyle.accentPetrol)
                        .foregroundStyle(.white)
                        .clipShape(RoundedRectangle(cornerRadius: 12))
                }
                .accessibilityLabel("Weiter zu den Fragen")

                Button(action: onSkip) {
                    Text("Überspringen")
                        .font(.subheadline.weight(.medium))
                        .foregroundStyle(.secondary)
                }
                .accessibilityLabel("Quiz überspringen")
            }
            .padding(.horizontal, NahbarInsightStyle.horizontalPadding)
            .padding(.bottom, 40)
        }
    }

    private func advance() {
        UserProfileStore.shared.updateGender(selected)
        onContinue()
    }
}

// MARK: - QuizQuestionsScreen

private struct QuizQuestionsScreen: View {
    let onComplete: (PersonalityProfile) -> Void
    let onSkip: () -> Void

    @State private var currentIndex = 0
    @State private var answers: [String: Bool] = [:]      // questionID → choseA
    @State private var selectedOption: OptionChoice? = nil
    @State private var isAdvancing = false

    private let questions = QuizQuestion.all

    var body: some View {
        VStack(spacing: 0) {
            progressDots
                .padding(.top, 24)
                .padding(.bottom, 28)

            // Fragen-Karten in ZStack für Slide-Transition
            ZStack {
                ForEach(Array(questions.enumerated()), id: \.element.id) { index, question in
                    if index == currentIndex {
                        questionContent(for: question)
                            .transition(NahbarInsightStyle.slideTransition)
                    }
                }
            }
            .clipped()
            .animation(.spring(response: 0.38, dampingFraction: 0.82), value: currentIndex)

            Spacer()

            Button(action: skipCurrentQuestion) {
                Text("Überspringen")
                    .font(.subheadline.weight(.medium))
                    .foregroundStyle(.secondary)
            }
            .padding(.bottom, 32)
        }
    }

    // MARK: Progress Dots

    private var progressDots: some View {
        HStack(spacing: 6) {
            ForEach(0..<questions.count, id: \.self) { index in
                Circle()
                    .fill(index <= currentIndex
                          ? NahbarInsightStyle.accentPetrol
                          : Color.secondary.opacity(0.3))
                    .frame(
                        width:  index == currentIndex
                            ? NahbarInsightStyle.progressDotActive
                            : NahbarInsightStyle.progressDotInactive,
                        height: index == currentIndex
                            ? NahbarInsightStyle.progressDotActive
                            : NahbarInsightStyle.progressDotInactive
                    )
                    .animation(.spring(response: 0.3), value: currentIndex)
            }
        }
        .accessibilityLabel("Frage \(currentIndex + 1) von \(questions.count)")
    }

    // MARK: Question Content

    @ViewBuilder
    private func questionContent(for question: QuizQuestion) -> some View {
        VStack(spacing: 20) {
            Text(question.situation)
                .font(NahbarInsightStyle.situationFont)
                .multilineTextAlignment(.center)
                .padding(NahbarInsightStyle.cardPadding)
                .frame(maxWidth: .infinity)
                .background(NahbarInsightStyle.cardBackground)
                .clipShape(RoundedRectangle(cornerRadius: NahbarInsightStyle.cardCornerRadius))
                .shadow(color: .black.opacity(0.06), radius: 8, x: 0, y: 2)
                .padding(.horizontal, NahbarInsightStyle.horizontalPadding)

            VStack(spacing: 12) {
                optionButton(text: question.optionA, choice: .a, question: question)
                optionButton(text: question.optionB, choice: .b, question: question)
            }
            .padding(.horizontal, NahbarInsightStyle.horizontalPadding)
        }
    }

    // MARK: Option Button

    @ViewBuilder
    private func optionButton(
        text: String,
        choice: OptionChoice,
        question: QuizQuestion
    ) -> some View {
        let isSelected = selectedOption == choice

        Button {
            guard !isAdvancing else { return }
            recordAnswer(choice, for: question)
        } label: {
            Text(text)
                .font(NahbarInsightStyle.optionFont)
                .multilineTextAlignment(.center)
                .frame(maxWidth: .infinity, minHeight: 64)
                .padding(.horizontal, 16)
                .padding(.vertical, 12)
                .background(
                    RoundedRectangle(cornerRadius: 12)
                        .fill(isSelected
                              ? NahbarInsightStyle.recommendedTint
                              : Color(.tertiarySystemBackground))
                        .overlay(
                            RoundedRectangle(cornerRadius: 12)
                                .strokeBorder(
                                    isSelected ? NahbarInsightStyle.accentPetrol : Color.clear,
                                    lineWidth: 2
                                )
                        )
                )
        }
        .buttonStyle(.plain)
        .animation(.easeInOut(duration: 0.15), value: isSelected)
        .accessibilityLabel(text)
        .accessibilityAddTraits(isSelected ? .isSelected : [])
    }

    // MARK: Logic

    private func recordAnswer(_ choice: OptionChoice, for question: QuizQuestion) {
        isAdvancing    = true
        selectedOption = choice
        UIImpactFeedbackGenerator(style: .light).impactOccurred()
        answers[question.id] = (choice == .a)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { advance() }
    }

    private func skipCurrentQuestion() {
        guard !isAdvancing else { return }
        isAdvancing = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { advance() }
    }

    private func advance() {
        let next = currentIndex + 1
        if next < questions.count {
            withAnimation { selectedOption = nil; currentIndex = next }
            isAdvancing = false
        } else {
            let profile = PersonalityEngine.computeProfile(
                from: answers.map { (questionID: $0.key, choseA: $0.value) }
            )
            PersonalityStore.shared.save(profile: profile)
            onComplete(profile)
        }
    }
}

// MARK: - OptionChoice

private enum OptionChoice: Equatable { case a, b }
