'use client'

import { useCallback, useEffect, useState } from "react";
import { optionLetters, questions } from "./questions";
import CountdownCircle from "@/components/countdown-circle";
import WaitingDots from "@/components/waiting-dots";
import Background from '../public/eu_bg.png';


enum QuizState {
  Idle,
  QuestionShown,
  QuestionIdle,
  QuestionAnswerShown
}

interface QuizProgress {
  usedQuestionIndexes: number[];
  questionIndex: number;
  currentQuestionId: number; // ha a kérdéseknek van id-ja, különben az indexet használd
}

export default function Home() {
  const [quizState, setQuizState] = useState<QuizState>(QuizState.Idle);

  const [showQuestion, setShowQuestion] = useState<boolean>(false);
  const [showAnswer, setShowAnswer] = useState<boolean>(false);

  const [showAnswerCounter, setShowAnswerCounter] = useState<number>(15);

  const [questionsList] = useState(() => [...questions]);
  //const [shuffled] = useState(() => [...questions].sort(() => Math.random() - 0.5));
  const [currentQuestion, setCurrentQuestion] = useState<Question>(questionsList[0]);

  const [questionIndex, setQuestionIndex] = useState(0);
  const [usedQuestionIndexes, setUsedQuestionIndexes] = useState<number[]>([]);

  // Betöltés local storage-ból
  useEffect(() => {
    const savedProgress = localStorage.getItem('quizProgress');
    if (savedProgress) {
      try {
        const progress: QuizProgress = JSON.parse(savedProgress);
        setUsedQuestionIndexes(progress.usedQuestionIndexes);
        setQuestionIndex(progress.questionIndex);

        // Ha van még felhasználatlan kérdés
        const unusedQuestions = questionsList.filter((_, idx) =>
          !progress.usedQuestionIndexes.includes(idx)
        );

        if (unusedQuestions.length > 0) {
          setCurrentQuestion(unusedQuestions[0]);
        } else {
          // Ha minden kérdést felhasználtunk, reseteljük
          resetQuiz();
        }
      } catch (error) {
        console.error('Error loading progress:', error);
      }
    }
  }, []);

  // Mentés local storage-ba
  useEffect(() => {
    const progress: QuizProgress = {
      usedQuestionIndexes,
      questionIndex,
      currentQuestionId: questionsList.findIndex(q => q === currentQuestion)
    };
    localStorage.setItem('quizProgress', JSON.stringify(progress));
  }, [usedQuestionIndexes, questionIndex, currentQuestion, questionsList]);


  useEffect(() => {
    const interval = setInterval(() => {
      setShowAnswerCounter(prev => {
        if (!showAnswer && showQuestion && prev >= 0 && quizState === QuizState.QuestionShown) {
          const next = prev - 1;
          if (next === -1) {
            setShowQuestion(false);
            setQuizState(QuizState.QuestionIdle);
          }
          return next;
        }
        return prev;
      });
    }, 1000);

    // cleanup on unmount
    return () => clearInterval(interval);
  }, [showAnswer, showQuestion, quizState]);

  // Random kérdés választás a fel nem használtak közül
  const getRandomUnusedQuestion = useCallback(() => {
    const availableIndexes = questionsList
      .map((_, idx) => idx)
      .filter(idx => !usedQuestionIndexes.includes(idx));

    if (availableIndexes.length === 0) {
      // Ha nincs több kérdés, reseteljük a quizt
      alert('A kérdések elfogytak. A kvíz újraindul.');
      resetQuiz();
      return null;
    }

    const randomIndex = availableIndexes[Math.floor(Math.random() * availableIndexes.length)];
    return {
      question: questionsList[randomIndex],
      index: randomIndex
    };
  }, [questionsList, usedQuestionIndexes]);

  // Reset funkció
  const resetQuiz = useCallback(() => {
    setUsedQuestionIndexes([]);
    setQuestionIndex(0);
    setQuizState(QuizState.Idle);
    setShowQuestion(false);
    setShowAnswer(false);
    setShowAnswerCounter(15);

    // Válassz egy random kérdést a reset után
    const randomIndex = Math.floor(Math.random() * questionsList.length);
    setCurrentQuestion(questionsList[randomIndex]);

    console.log("A quiz resetelve lett!");

    // Töröld a local storage-t is
    localStorage.removeItem('quizProgress');
  }, [questionsList]);


  const handleNext = useCallback(async () => {
    if (quizState === QuizState.Idle || quizState === QuizState.QuestionAnswerShown) {
      setQuizState(QuizState.QuestionShown);
      setShowAnswer(false);

      // Új kérdés választása
      const newQuestionData = getRandomUnusedQuestion();

      if (!newQuestionData) {
        // Ha nincs több kérdés, reset
        resetQuiz();
        return;
      }

      // Jelöld meg a kérdést használtként
      setUsedQuestionIndexes(prev => [...prev, newQuestionData.index]);
      setQuestionIndex(prev => prev + 1);
      setCurrentQuestion(newQuestionData.question);

      const answerIndex = newQuestionData.question.options.findIndex(
        option => option === newQuestionData.question.answer
      );

      console.log(`${questionIndex + 1}. Helyes válasz: ${optionLetters[answerIndex]}) ${newQuestionData.question.answer}`);
      setShowAnswerCounter(15);
      setShowQuestion(true);
    }

    else if (quizState === QuizState.QuestionShown) {
      if (showAnswerCounter > 0) {
        setQuizState(QuizState.QuestionAnswerShown);
        setShowAnswerCounter(0);
        setShowAnswer(true);
        return;
      }

      setQuizState(QuizState.QuestionIdle);
      setShowQuestion(false);
      setShowAnswerCounter(0);
    }

    else if (quizState === QuizState.QuestionIdle) {
      setQuizState(QuizState.QuestionAnswerShown);
      setShowQuestion(true);
      setShowAnswer(true);
      setShowAnswerCounter(0);
    }

  }, [quizState, showAnswerCounter, getRandomUnusedQuestion, questionIndex, usedQuestionIndexes.length, questionsList.length, resetQuiz]);

  // bg-zinc-50 dark:bg-neutral-950
  const opacity = quizState === QuizState.Idle ? "bg-neutral-950/50" : "bg-neutral-950/90";
  return (
    <div
      className="h-screen w-screen flex justify-center flex-1 font-sans"
      style={{ backgroundImage: `url(${Background.src})`, backgroundSize: 'cover', backgroundPosition: 'center' }}
    >
      <div className={`absolute inset-0 ${opacity} transition-all duration-500 ease-in-out`} />
      <div className="z-10">
        {/* <div className="absolute bottom-4 left-4">
          <ThemeToggle />
        </div> */}

        {showQuestion ? (
          <div className="flex flex-col gap-14 items-center mt-48">
            <CountdownCircle value={showAnswerCounter} max={15} size={80} strokeWidth={4} />

            <div className={`flex ${quizState === QuizState.QuestionShown ? "animate-slide-up" : ""}`}>
              <p className="text-4xl font-bold text-neutral-100">{questionIndex}. {currentQuestion.question}</p>
            </div>

            <div key={questionIndex} className="flex flex-col gap-6">
              {currentQuestion.options.map((option, idx) => (
                <p key={idx} style={{ animationDelay: `${idx * 80 + 120}ms` }} className={`${quizState === QuizState.QuestionShown ? "animate-slide-up" : ""} text-3xl ${option == currentQuestion.answer && showAnswer ? "text-green-500" : "text-neutral-100"}`}
                >{optionLetters[idx]}) {option}</p>
              ))}
            </div>
          </div>
        ) : (
          <div className="mt-48">
            {quizState === QuizState.Idle && (
              <>
                <WaitingDots className="text-4xl inline-block w-[400px]" text="Várakozás az indításra" />
                <div className="absolute bottom-4 right-4 py-1 px-2">
                  <p className="text-neutral-300 text-lg">A weboldalt készítette és üzemelteti: Kovács Balázs 13.D</p>
                </div>
              </>
            )}
            {quizState === QuizState.QuestionIdle && (
              <div className="flex flex-col items-center justify-center gap-4">
                <p className="text-neutral-100 text-4xl">Az idő lejárt.</p>
                <WaitingDots className="text-4xl inline-block w-48" text="Várakozás" />
              </div>
            )}
          </div>
        )
        }
        <button className="absolute top-4 right-4 py-1 px-2 bg-blue-800 shadow-md rounded-lg hover:bg-blue-700 duration-150 hover:shadow-lg active:scale-95"
          onClick={handleNext}>
          <p className="text-neutral-100 text-lg">Következő</p>
        </button>
        <button className="absolute bottom-4 left-4 py-1 px-2 bg-red-800 shadow-md rounded-lg hover:bg-red-700 duration-150 hover:shadow-lg active:scale-95"
          onClick={resetQuiz}>
          <p className="text-neutral-100 text-lg">Reset</p>
        </button>
      </div>
    </div>
  );
}
