import { useState, useCallback } from 'react';
import type { Audit, UserAnswer, ScoreResult, QuizStep } from '../types';
import { calculateScore } from '../engine/scoring';

interface UseQuizReturn {
  step: QuizStep;
  currentQuestion: number;
  answers: UserAnswer[];
  scoreResult: ScoreResult | null;
  totalQuestions: number;
  progress: number;
  selectAnswer: (answerIndex: number) => void;
  goBack: () => void;
  startQuiz: () => void;
  submitEmail: () => void;
}

export function useQuiz(audit: Audit | null): UseQuizReturn {
  const [step, setStep] = useState<QuizStep>('landing');
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [answers, setAnswers] = useState<UserAnswer[]>([]);
  const [scoreResult, setScoreResult] = useState<ScoreResult | null>(null);

  const totalQuestions = audit?.questions.length ?? 0;
  const progress = totalQuestions > 0 ? Math.round((currentQuestion / totalQuestions) * 100) : 0;

  const startQuiz = useCallback(() => {
    setStep('quiz');
    setCurrentQuestion(0);
    setAnswers([]);
    setScoreResult(null);
  }, []);

  const selectAnswer = useCallback(
    (answerIndex: number) => {
      if (!audit) return;

      const question = audit.questions[currentQuestion];
      const answer = question.answers[answerIndex];

      const newAnswer: UserAnswer = {
        questionId: question.id,
        categoryId: question.categoryId,
        answerIndex,
        points: answer.points,
      };

      setAnswers((prev) => {
        // Replace if already answered this question (going back).
        const filtered = prev.filter((a) => a.questionId !== question.id);
        return [...filtered, newAnswer];
      });

      // Auto-advance after a brief delay for animation.
      setTimeout(() => {
        if (currentQuestion < totalQuestions - 1) {
          setCurrentQuestion((prev) => prev + 1);
        } else {
          // Last question — calculate score and show email gate.
          const allAnswers = [
            ...answers.filter((a) => a.questionId !== question.id),
            newAnswer,
          ];
          const result = calculateScore(audit, allAnswers);
          setScoreResult(result);
          setStep('email-gate');
        }
      }, 400);
    },
    [audit, currentQuestion, totalQuestions, answers]
  );

  const goBack = useCallback(() => {
    if (currentQuestion > 0) {
      setCurrentQuestion((prev) => prev - 1);
    } else {
      setStep('landing');
    }
  }, [currentQuestion]);

  const submitEmail = useCallback(() => {
    setStep('results');
  }, []);

  return {
    step,
    currentQuestion,
    answers,
    scoreResult,
    totalQuestions,
    progress,
    selectAnswer,
    goBack,
    startQuiz,
    submitEmail,
  };
}
