import { useEffect, useState } from 'react';
import { useParams } from 'react-router';

import { listMatchingFrenzyContent } from '../../public_data';
import { IonContent, IonIcon, IonPage, useIonRouter } from '@ionic/react';
import { alarmOutline } from 'ionicons/icons';

import { LoadingScreen } from '../../components/LoadingScreen';
import IMatchingFrenzyQuestion from '../../interfaces/IMatchingFrenzyQuestion';
import { MATCHING_FRENZY_LINK, QUIZ_MAIN_MENU_LINK } from '../../constants';
import MatchingFrenzyCard from './MatchingFrenzyCard';
import { useMyIonQuizContext } from '../../contexts/MyIonQuiz';
import PressStartToBegin from './PressStartToBegin';
import { useAppStateContext } from '../../contexts/AppState';
import { shuffleArray } from '../../utils/shuffleArray';
import CountDown from './CountDown';

import './style.css';

function MatchingFrenzyMatchRun() {
  const [loading, setLoading] = useState<boolean>(true);

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

  const [question_list, setQuestionList] = useState<IMatchingFrenzyQuestion[] | []>([]);
  const [current_question_meta, setCurrentQuestionMeta] = useState<IMatchingFrenzyQuestion | undefined>(undefined);

  const [current_question, setCurrentQuestion] = useState(0);
  const [num_correct, setNumCorrect] = useState(0);

  const { setTabActive } = useAppStateContext();

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

  const [countdown_s, setCountDown_s] = useState<number>(120);
  const [show_time_left_s, setShowTimeLeft] = useState<string>('0:00');
  const { setMatchingFrenzyInProgress } = useAppStateContext();
  const { setMatchingFrenzyCurrentTest, setMatchingFrenzyResult, saveMatchingFrenzyResultToScoreBoard } =
    useMyIonQuizContext();

  let [start_match, setStartMatch] = useState(false);
  let [test_random, setTestRandom] = useState(0);

  const formatTimeDisplay = (s: number) => {
    return `${Math.floor(s / 60)}:${(s % 60).toString().padStart(2, '0')}`;
  };

  const nextQuestion = () => {
    if (isEndOfQuestionList(current_question, question_list)) {
      let num_correct_result = num_correct + 1;
      setMatchingFrenzyCurrentTest(i_p_route);
      setMatchingFrenzyResult(num_correct_result);

      saveMatchingFrenzyResultToScoreBoard(p_route, {
        //
        date: new Date().toISOString().slice(0, 10),
        result: num_correct_result
      });
      //
      router.push(`${MATCHING_FRENZY_LINK}/finished`, 'none', 'replace');
    } else {
      let next_question_num = current_question + 1;
      setCurrentQuestion(next_question_num);
      setCurrentQuestionMeta(question_list[next_question_num]);
    }
  };

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

  function processStartMatch() {
    setMatchingFrenzyInProgress(true);
    setStartMatch(true);
  }

  useEffect(() => {
    setShowTimeLeft(formatTimeDisplay(countdown_s));

    if (countdown_s <= 0) {
      setMatchingFrenzyCurrentTest(i_p_route);
      setMatchingFrenzyResult(num_correct);

      saveMatchingFrenzyResultToScoreBoard(p_route, {
        //
        date: new Date().toISOString().slice(0, 10),
        result: num_correct
      });
      //
      router.push(`${MATCHING_FRENZY_LINK}/finished`, 'none', 'replace');
    }
  }, [countdown_s]);

  const [init_ans, setInitAns] = useState<string[]>([]);

  useEffect(() => {
    if (!current_question_meta) return;
    let init_options = [...question_list.map(q => q.word), ...answer_list, ...init_ans];

    let all_answer_list = [...new Set(init_options)];
    let wrong_answer_list = all_answer_list.filter(a => a !== current_question_meta.word);
    let answer_list_shuffle = shuffleArray(wrong_answer_list);
    let sliced_shuffle_array = shuffleArray(answer_list_shuffle).slice(0, 2 + 1);

    setAnswerList(shuffleArray([...sliced_shuffle_array, current_question_meta.word]));
  }, [current_question_meta]);

  useEffect(() => {
    (async () => {
      const res_json = await listMatchingFrenzyContent();
      const cat_json = res_json[i_p_route];
      const init_answer = cat_json.init_answer;
      setInitAns(cat_json.init_answer);

      let temp = res_json[i_p_route].content;
      let shuffled_temp = shuffleArray(temp);

      setQuestionList(shuffled_temp);
      setCurrentQuestionMeta(cat_json.content[current_question]);
    })();

    setTabActive(QUIZ_MAIN_MENU_LINK);
    setTestRandom(Math.random());
  }, []);

  if (!current_question_meta) return <LoadingScreen />;

  return (
    <>
      <IonPage>
        <IonContent fullscreen>
          {start_match ? (
            <>
              <div style={{ margin: '1rem' }}>
                <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between' }}>
                  <div style={{ display: 'flex', flexDirection: 'row', gap: '0.3rem' }}>
                    <IonIcon icon={alarmOutline}></IonIcon>
                    {countdown_s > 0 ? show_time_left_s : 'times up'}
                  </div>
                  <div>Matches:{num_correct}</div>
                </div>
                <MatchingFrenzyCard
                  num_correct={num_correct}
                  incNumCorrect={incNumCorrect}
                  //
                  nextQuestion={nextQuestion}
                  question_meta={{
                    //
                    word_c: current_question_meta.word_c,
                    modal_answer: current_question_meta.word
                  }}
                  shuffle_word_list={answer_list}
                />
              </div>
            </>
          ) : (
            <PressStartToBegin processStartMatch={processStartMatch} />
          )}

          <CountDown start_match={start_match} init_time_left_s={countdown_s} setCountDown_s={setCountDown_s} />
        </IonContent>
      </IonPage>
    </>
  );
}

export default MatchingFrenzyMatchRun;
function isEndOfQuestionList(current_question: number, question_list: [] | IMatchingFrenzyQuestion[]) {
  return current_question >= question_list.length - 1;
}
