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

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

  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 { setConnectiveRevisionCurrentTest, setConnectiveRevisionProgress } = 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));
      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 listConectivesRevisionContent();
      let temp_init_ans = res_json[i_p_route].init_ans;

      setInitAnswer(temp_init_ans);
      let temp = res_json[i_p_route].content;
      let shuffled_temp = shuffleArray(temp);
      // let shuffled_temp = temp;
      setQuestionList(shuffled_temp);

      let question_meta_current = res_json[i_p_route].content[0];
      setCurrentQuestionMeta({
        question_idx: current_question_idx,
        ...question_meta_current
      });
    })();
    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}
            //
          />
          {/*  */}
          {/*  */}
          <CorrectAnswerToast isOpen={isOpenCorrectAnswer} dismiss={() => setIsOpenCorrectAnswer(false)} />
          {/*  */}
          <WrongAnswerToast isOpen={isOpenWrongAnswer} dismiss={() => setIsOpenWrongAnswer(false)} />
          {/* 
          <IonToast
            isOpen={isOpenCorrectAnswer}
            message='This answer is correct'
            onDidDismiss={() => setIsOpenCorrectAnswer(false)}
            duration={1000 - 100}
            color='success'
          ></IonToast>
          <IonToast
            isOpen={isOpenWrongAnswer}
            message='This answer is wrong'
            onDidDismiss={() => setIsOpenWrongAnswer(false)}
            duration={1000 - 100}
            color='danger'
          ></IonToast> */}
        </IonContent>
      </IonPage>
    </>
  );
}

export default ConnectiveRevisionQuizRun;
