import React, { useState, useEffect, useMemo } from "react";
import styles from "./index.module.scss";
import { shuffle, generateThreeOptions, questions } from "../../assets/data/questions";
import { getSessionStorage, setSessionStorage, clearSessionStorage } from "../../utils/storage";
import { useNavigate } from "react-router-dom";
import dayjs from "dayjs";
import Result from "./components/index";

interface QuestionItem {
  id: number;
  title: string;
  isClicked?: boolean;
  options: { id: number; title: string }[];
}

interface QuestionProps {
  randomQuestions: QuestionItem[];
  item: QuestionItem;
  setItem: (item: QuestionItem) => void;
  currentIndex: number;
  setCurrentIndex: (index: number) => void;
  setIsFinish: (isFinish: boolean) => void;
  setRightCount: (rightCount: number) => void;
}

const Question = ({ randomQuestions, item, setItem, currentIndex, setCurrentIndex, setIsFinish, setRightCount }: QuestionProps) => {
  const sentence = item.title.split("——")[0];
  const from = item.title.split("——")[1];
  const [questionStatus, setQuestionStatus] = useState(["or", "or", "or", "or", "or", "or", "or", "or", "or", "or"]);
  let isClicked: boolean = getSessionStorage(`question${currentIndex}`)?.isClicked ?? false;

  useEffect(() => {
    // eslint-disable-next-line react-hooks/exhaustive-deps
    isClicked = getSessionStorage(`question${currentIndex}`)?.isClicked ?? false;
  }, [currentIndex])

  const handleBtnClick = (id: number) => {
    if (isClicked) return;
    isClicked = true
    const currentStatus = questionStatus.map((status, index) => index === currentIndex ? id === 1 ? "true" : "false" : status)
    setQuestionStatus(currentStatus)
    setItem({ ...item, isClicked: true })
    setSessionStorage(`question${currentIndex}`, { ...item, isClicked: true })
    setTimeout(() => {
      if (currentStatus.every(status => status === "true" || status === "false")) {
        setRightCount(currentStatus.filter(status => status === "true").length)

        setIsFinish(true)
      } else {
        if (currentIndex === 9) {
          const index = currentStatus.findIndex((status, index) => { return status === "or" })
          handleBannerClick(index)
        } else {
          handleBannerClick(currentIndex + 1)
        }
      }
    }, 1000)
  }

  const handleBannerClick = (newIndex: number) => {
    setItem(getSessionStorage(`question${newIndex}`) ?? randomQuestions[newIndex]);
    setCurrentIndex(newIndex)
    setSessionStorage(`question${currentIndex}`, { ...item, isClicked: isClicked })
  }

  const chineseNumbers = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]
  return (
    <>
      <div className="banner">
        {questionStatus.map((status, index) => (
          <img key={index} src={require(`../../assets/img/${status}.png`)} onClick={() => handleBannerClick(index)} alt="banner" />
        ))}
      </div>
      <div className="title">题目{chineseNumbers[currentIndex]}</div>
      <div className="questions">
        <div className="content">
          {sentence}
        </div>
        <div className="from"> ——{from}</div>
      </div>
      <div className="btn-group" >
        <div className="option1" onClick={() => handleBtnClick(item.options[0].id)}>
          <span>{item.options[0].title}</span>
          {item.isClicked && <img src={require(`../../assets/img/option_${item.options[0].id === 1 ? "true" : "false"}.png`)} alt="" />}
        </div>
        <div className="option2" onClick={() => handleBtnClick(item.options[1].id)} >
          <span>{item.options[1].title}</span>
          {item.isClicked && <img src={require(`../../assets/img/option_${item.options[1].id === 1 ? "true" : "false"}.png`)} alt="" />}
        </div>
        <div className="option3" onClick={() => handleBtnClick(item.options[2].id)}>
          <span>{item.options[2].title}</span>
          {item.isClicked && <img src={require(`../../assets/img/option_${item.options[2].id === 1 ? "true" : "false"}.png`)} alt="" />}
        </div>
      </div>
    </>
  );
};

const QuestionList = () => {
  const randomQuestions: QuestionItem[] = useMemo(() => {
    return (shuffle(questions.map((questionArray) => {
      const question = shuffle(questionArray)[0];
      return {
        ...question,
        options: generateThreeOptions(question.options),
      };
    })) as QuestionItem[])
  }, [])
  const [item, setItem] = useState<QuestionItem>(randomQuestions[0]);
  const [index, setIndex] = useState(0);
  const [timeLeft, setTimeLeft] = useState(180);
  const [isFinish, setIsFinish] = useState(false)
  const [rightCount, setRightCount] = useState(0)

  const navigate = useNavigate()

  useEffect(() => {
    clearSessionStorage()
    const timer = setInterval(() => {
      setTimeLeft((prevTime) => {
        if (prevTime <= 0) {
          clearInterval(timer);
          setIsFinish(true)
          return 0;
        }
        return prevTime - 1;
      });
    }, 1000);

    if (isFinish) {
      clearInterval(timer);
    }
    return () => clearInterval(timer);
  }, [isFinish])


  return (
    isFinish ? (
      <Result timeLeft={timeLeft} rightCount={rightCount} />
    ) : (
      <div className={styles.question}>
        <Question
          randomQuestions={randomQuestions}
          item={item}
          setItem={setItem}
          currentIndex={index}
          setCurrentIndex={setIndex}
          setIsFinish={setIsFinish}
          setRightCount={setRightCount}
        />
        <div className="tips">请输入正确的文字</div>
        <div className="back" onClick={() => navigate("/")}>
          <img src={require("../../assets/img/back.png")} alt="back" />
        </div>
        <div className="time">
          <img src={require("../../assets/img/time.png")} alt="time" />
          <div className="time-text">{dayjs().startOf('day').second(timeLeft).format('mm:ss')}</div>
        </div>
      </div>
    )
  );
};

export default QuestionList;
