import { IonContent, IonPage, useIonRouter } from '@ionic/react';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router';
import { LoadingScreen } from '../../components/LoadingScreen';
import { CONNECTIVE_REVISION_LINK, QUIZ_MAIN_MENU_LINK } from '../../constants';
import { useAppStateContext } from '../../contexts/AppState';
import { useMyIonQuizContext } from '../../contexts/MyIonQuiz';
import { listConectivesRevisionContent } from '../../public_data/listConectivesRevisionContent';
import { shuffleArray } from '../../utils/shuffleArray';
import QuizContent from './QuizContent';
import fetchCRQuestions from '../../hooks/fetchCRQuestions';
import { usePocketBase } from '../../hooks/usePocketBase';

function ConnectiveRevisionQuizRun() {
  const router = useIonRouter();
  const { p_route: cat_id } = useParams<{ p_route: string }>();

  // NOTE: abonded, should be updated with `i_cat_id` when done
  const i_p_route = parseInt(cat_id);

  const { setTabActive } = useAppStateContext();
  const [question_list, setQuestionList] = useState<IQuestionJson[] | []>([]);
  const [current_question_meta, setCurrentQuestionMeta] = useState<IQuestionMeta | undefined>(undefined);
  const [current_question_idx, setCurrentQuestionIdx] = useState(0);
  const [num_correct, setNumCorrect] = useState(0);
  const [isOpenCorrectAnswer, setIsOpenCorrectAnswer] = useState(false);
  const [isOpenWrongAnswer, setIsOpenWrongAnswer] = useState(false);
  const [answer_list, setAnswerList] = useState<string[]>(['but', 'and', 'or', 'of', 'with']);

  const { user, pb } = usePocketBase();

  const {
    setConnectiveRevisionCurrentTest,
    setConnectiveRevisionProgress,
    setConnectiveRevisionScore,
    //
  } = useMyIonQuizContext();
  const { setConnectiveRevisionInProgress } = useAppStateContext();

  function openCorrectToast() {
    setIsOpenCorrectAnswer(true);
  }

  function openWrongToast() {
    setIsOpenWrongAnswer(true);
  }

  const nextQuestion = () => {
    let next_question_num = current_question_idx + 1;

    setCurrentQuestionIdx(next_question_num);
    // setCurrentQuestionMeta(question_list[next_question_num]);
    let question_meta_current = question_list[next_question_num];
    setCurrentQuestionMeta({
      question_idx: next_question_num,
      ...question_meta_current,
    });

    if (next_question_num >= question_list.length) {
      setConnectiveRevisionCurrentTest(i_p_route);

      // setConnectiveRevisionProgress(Math.ceil(((num_correct + 1) / question_list.length) * 100));
      setConnectiveRevisionScore(Math.ceil((num_correct / question_list.length) * 100));

      router.push(`${CONNECTIVE_REVISION_LINK}/finished`, 'none', 'replace');
    }
  };

  const incNumCorrect = () => {
    setNumCorrect(num_correct + 1);
  };

  const [init_answer, setInitAnswer] = useState<string[]>([]);

  useEffect(() => {
    if (!current_question_meta) return;

    // let all_answers = [...new Set([...question_list.map(q => q.modal_ans), ...current_question_meta.options])];
    let all_answers = [current_question_meta.modal_ans, ...current_question_meta.options];

    let wrong_ans_list = all_answers.filter((a) => a !== current_question_meta.modal_ans);
    let sliced_shuffle_array = shuffleArray(wrong_ans_list).slice(0, 2);
    let full_array = [...sliced_shuffle_array, current_question_meta.modal_ans];
    setAnswerList(shuffleArray(full_array));
  }, [current_question_meta]);

  useEffect(() => {
    (async () => {
      const res_json = await fetchCRQuestions(cat_id, pb);
      let temp_init_ans: string[] = res_json.items[0].init_answer;

      setInitAnswer(temp_init_ans);
      let temp = res_json.items;
      let shuffled_temp = shuffleArray(temp);
      // let shuffled_temp = temp;
      setQuestionList(shuffled_temp);

      let question_meta_current = res_json.items[0] as unknown as IQuestionMeta;
      setCurrentQuestionMeta({
        ...question_meta_current,
        question_idx: current_question_idx,
      });
    })();
    setTabActive(QUIZ_MAIN_MENU_LINK);
  }, []);

  if (!current_question_meta) return <LoadingScreen />;

  return (
    <>
      <IonPage>
        <IonContent fullscreen>
          <QuizContent
            num_correct={num_correct}
            incNumCorrect={incNumCorrect}
            nextQuestion={nextQuestion}
            question_meta={current_question_meta}
            // openCorrectToast={openCorrectToast}
            // openWrongToast={openWrongToast}
            total_questions_num={question_list.length}
            answer_list={answer_list}
            quiz_idx={i_p_route + 1}
          />
        </IonContent>
      </IonPage>
    </>
  );
}

export default ConnectiveRevisionQuizRun;
