import { useEffect, useState } from 'react';
import { useParams } from 'react-router';
import { IonContent, IonPage, useIonRouter } from '@ionic/react';
import { LISTENING_PRACTICE_LINK } from '../../../constants';

import './style.css';
import ListeningPracticeQuestionCard from './ListeningPracticeQuestionCard';
import { listQuizListeningPracticeContent } from '../../../public_data';
import IListeningPracticeQuestion from '../../../interfaces/IListeningPracticeQuestion';
import { LoadingScreen } from '../../../components/LoadingScreen';
import { useMyIonMetric } from '../../../contexts/MyIonMetric';
import { useMyIonQuizContext } from '../../../contexts/MyIonQuiz';
import { shuffleArray } from '../../../utils/shuffleArray';
import { useFullmarkCount } from '../../../contexts/MyIonMetric/FullmarkCount';

const QuestionRoute: React.FC = () => {
  const { p_route } = useParams<{ p_route: string }>();
  const i_p_route = parseInt(p_route);
  const [question_list, setQuestionList] = useState<IListeningPracticeQuestion[] | []>([]);
  const [current_question_meta, setCurrentQuestionMeta] = useState<IListeningPracticeQuestion | undefined>(undefined);

  const [current_question_idx, setCurrentQuestionIdx] = useState(0);
  const [num_correct, setNumCorrect] = useState(0);
  const { myIonMetricIncFullMarkCount } = useFullmarkCount();
  const { listening_practice_result, setListeningPracticeResult, setListeningPracticeCurrentTest } =
    useMyIonQuizContext();

  const { listening_practice_correction_list, setListeningPracticeCorrectionList } = useMyIonQuizContext();
  const [question_finished, setQuestionFinished] = useState(false);

  const router = useIonRouter();
  const nextQuestion = () => {
    if (current_question_idx >= question_list.length - 1) {
      setQuestionFinished(true);
      // if (isCorrectionNeeded()) {
      //   // run correction phase
      //   router.push(`${LISTENING_PRACTICE_LINK}/c/0`, 'none', 'replace');
      // } else {
      //   router.push(`${LISTENING_PRACTICE_LINK}/finished`, 'none', 'replace');
      // }
    } else {
      setCurrentQuestionIdx(current_question_idx + 1);
      setCurrentQuestionMeta(question_list[current_question_idx + 1]);
    }
  };

  useEffect(() => {
    let isCorrectionNeeded = () => listening_practice_correction_list.length > 0;

    if (question_finished) {
      if (isCorrectionNeeded()) {
        // run correction phase
        router.push(`${LISTENING_PRACTICE_LINK}/c/0`, 'none', 'replace');
      } else {
        router.push(`${LISTENING_PRACTICE_LINK}/finished`, 'none', 'replace');
      }
    }
  }, [question_finished]);

  const incNumCorrect = () => {
    setNumCorrect(num_correct + 1);
    let temp: number = Math.ceil(((num_correct + 1) / question_list.length) * 100);
    setListeningPracticeResult(temp);
    setListeningPracticeCurrentTest(i_p_route);
    myIonMetricIncFullMarkCount();
  };

  let [answer_list, setAnswerList] = useState<string[]>([]);

  useEffect(() => {
    (async () => {
      const res_json = await listQuizListeningPracticeContent();

      let init_answer = res_json[i_p_route].init_answer;
      let temp = res_json[i_p_route].content;
      let shuffled_temp = shuffleArray(temp);
      setQuestionList(shuffled_temp);
      setAnswerList([...new Set([...init_answer, ...temp.map((t: IListeningPracticeQuestion) => t.word)])]);
      setCurrentQuestionMeta(res_json[i_p_route].content[current_question_idx]);
    })();
  }, []);

  if (!current_question_meta) return <LoadingScreen />;

  return (
    <IonPage>
      <IonContent fullscreen>
        <ListeningPracticeQuestionCard
          num_correct={num_correct}
          incNumCorrect={incNumCorrect}
          //
          question_num={current_question_idx}
          nextQuestion={nextQuestion}
          //
          total_questions={question_list.length}
          //
          question_meta={{
            //
            sound: current_question_meta.sound,
            modal_answer: current_question_meta.word
          }}
          //
          answer_list={answer_list}
          //
          question={current_question_meta}
        />
      </IonContent>
    </IonPage>
  );
};

export default QuestionRoute;
