import { IonButton, IonIcon } from '@ionic/react';
// import QuestionProgress from './QuestionProgress';
import QuestionProgress from '../../../components/QuestionProgress';
import { useEffect, useRef, useState } from 'react';
import { SpeakerImage } from '../../../components/SpeakerImage';
import { useGlobalAudioPlayer } from 'react-use-audio-player';
// import { AudioControls } from '../../LessonWord/AudioControls';
import { LoadingScreen } from '../../../components/LoadingScreen';
import { AudioControls } from './AudioControls';
import { volumeHighOutline, play } from 'ionicons/icons';
import { useMyIonQuizContext } from '../../../contexts/MyIonQuiz';
import IListeningPracticeQuestion from '../../../interfaces/IListeningPracticeQuestion';
import { COLOR_TEXT, DEBUG } from '../../../constants';
import CorrectAnswerToast from '../../../components/CorrectAnswerToast';
import WrongAnswerToast from '../../../components/WrongAnswerToast';

import './style.css';

interface QuestionCardProps {
  question_num: number;
  nextQuestion: () => void;
  num_correct: number;
  incNumCorrect: () => void;
  question_meta: any;
  total_questions: number;
  answer_list: string[];
  question: IListeningPracticeQuestion;
}

const ListeningPracticeQuestionCard: React.FC<QuestionCardProps> = ({
  num_correct,
  question_num,
  nextQuestion,
  incNumCorrect,
  total_questions,
  question_meta,
  answer_list,
  question
}) => {
  const [loading, setLoading] = useState(true);
  //
  const [isOpenCorrectAnswer, setIsOpenCorrectAnswer] = useState(false);
  const [isOpenWrongAnswer, setIsOpenWrongAnswer] = useState(false);
  //
  const [ignore_answer_button, setIgnoreAnswerButton] = useState(false);

  const [user_answer, setUserAnswer] = useState<string | undefined>(undefined);
  const [modal_answer, setModalAnswer] = useState(question_meta.modal_answer);
  const { play: play_word, playing } = useGlobalAudioPlayer();
  const [playing_audio, setPlayingAudio] = useState(true);
  let [disable_user_answer, setDisableUserAnswer] = useState(true);
  let { appendToListeningPracticeCorrectionList } = useMyIonQuizContext();

  function handleUserAnswer(answer: string, e: React.MouseEvent, ref_button: React.RefObject<HTMLIonButtonElement>) {
    setUserAnswer(answer);

    if (!ignore_answer_button) {
      console.log('shoule see me one only !!!');
      if (answer.toLowerCase() === modal_answer.toLowerCase()) {
        incNumCorrect();
        setIsOpenCorrectAnswer(true);
        if (ref_button && ref_button.current) ref_button.current.style.backgroundColor = 'green';
        if (ref_button && ref_button.current) ref_button.current.style.color = 'white';
      } else {
        console.log('wrong answer checked');
        setIsOpenWrongAnswer(true);
        if (ref_button && ref_button.current) ref_button.current.style.backgroundColor = 'red';
        if (ref_button && ref_button.current) ref_button.current.style.color = 'white';

        appendToListeningPracticeCorrectionList(question);
      }

      setTimeout(() => {
        nextQuestion();
        setPlayingAudio(true);
      }, 3000);
    }
  }

  useEffect(() => {
    if (playing_audio) {
      setDisableUserAnswer(true);
      setIgnoreAnswerButton(true);
    } else {
      setDisableUserAnswer(false);
      setIgnoreAnswerButton(false);
    }
  }, [playing_audio]);

  function playAudio() {
    setPlayingAudio(true);
    play_word();
    setTimeout(() => {
      setPlayingAudio(false);
    }, 1000);
  }

  function delayedPlayAudio() {
    setPlayingAudio(true);
    setTimeout(() => {
      playAudio();
    }, 1000);
  }

  let ref1 = useRef<HTMLIonButtonElement>(null);
  let ref2 = useRef<HTMLIonButtonElement>(null);
  let ref3 = useRef<HTMLIonButtonElement>(null);
  let ref4 = useRef<HTMLIonButtonElement>(null);
  let button_refs = [ref1, ref2, ref3, ref4];

  function resetButtonFace(ref_button: React.RefObject<HTMLIonButtonElement>) {
    if (ref_button && ref_button.current) ref_button.current.style.backgroundColor = 'unset';
    if (ref_button && ref_button.current) ref_button.current.style.color = 'unset';
  }

  useEffect(() => {
    resetButtonFace(ref1);
    resetButtonFace(ref2);
    resetButtonFace(ref3);
    resetButtonFace(ref4);
  }, [question_num, ref1, ref2, ref3, ref4]);

  function getAnswerList(modal_answer: string) {
    let wrong_answer_list = answer_list.filter(a => a !== modal_answer);
    let sliced_shuffle_array = shuffleArray(wrong_answer_list).slice(0, 2);
    let full_array = [...sliced_shuffle_array, modal_answer];
    return shuffleArray(full_array);
  }

  let [last_shuffle, setLastShuffle] = useState<string[]>([]);
  let [shuffled_answer, setShuffledAnswer] = useState<string[]>([]);

  useEffect(() => {
    setDisableUserAnswer(true);

    let { modal_answer } = question_meta;
    let temp: string[] = getAnswerList(modal_answer);
    if (last_shuffle.length == 0) {
      setLastShuffle(temp);
      setShuffledAnswer(temp);
    } else {
      for (let i = 0; i < 99; i++) {
        let temp: string[] = getAnswerList(modal_answer);

        if (JSON.stringify(last_shuffle) !== JSON.stringify(temp)) {
          setLastShuffle(temp);
          setShuffledAnswer(temp);
          break;
        }
      }
    }

    delayedPlayAudio();

    setModalAnswer(modal_answer);
  }, [question_num]);

  const { resetListeningPracticeCorrectionList } = useMyIonQuizContext();
  useEffect(() => {
    setLoading(false);

    resetListeningPracticeCorrectionList();
  }, []);

  if (loading) return <LoadingScreen />;
  if (!question_meta) return <LoadingScreen />;

  return (
    <>
      <div
        style={{
          marginTop: '5rem',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center'
        }}
      >
        <div style={{ marginTop: '1rem', marginBottom: '1rem' }}>
          <QuestionProgress num_rating={num_correct} num_full_rating={total_questions} />
        </div>
        <div>Question card {question_num + 1}</div>
        <div style={{ margin: '1rem 0rem', width: '33vw', height: '33vw' }}>
          <SpeakerImage />
        </div>

        {DEBUG ? (
          <div className='debug'>
            {JSON.stringify(question_meta)}
            {JSON.stringify(question.word)}
          </div>
        ) : null}

        <IonButton color={COLOR_TEXT} disabled={playing_audio} shape='round' fill='clear' onClick={() => playAudio()}>
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              justifyContent: 'center',
              alignItems: 'center',
              gap: '0.5rem',
              color: COLOR_TEXT
            }}
          >
            <IonIcon slot='icon-only' size='large' icon={playing_audio ? play : volumeHighOutline}></IonIcon>
            <div>{playing_audio ? 'playing' : 'repeat'}</div>
          </div>
        </IonButton>

        <div
          style={{
            marginTop: '3rem',
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center',
            minWidth: '50vw'
          }}
        >
          {DEBUG ? <div className='debug'>{JSON.stringify(modal_answer)}</div> : null}

          {playing_audio ? (
            <div style={{ fontSize: '1.1rem', fontWeight: 'bold' }}>Listen</div>
          ) : (
            <div style={{ color: COLOR_TEXT }}>Select the word you heard</div>
          )}
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              gap: '1rem',
              marginTop: '1rem',
              minWidth: '50vw'
            }}
          >
            {shuffled_answer.map((word, index) => {
              return (
                <div>
                  <IonButton
                    color='dark'
                    expand='block'
                    fill='outline'
                    ref={button_refs[index]}
                    disabled={disable_user_answer}
                    onClick={e => {
                      setIgnoreAnswerButton(true);
                      handleUserAnswer(word, e, button_refs[index]);
                    }}
                  >
                    {word}
                  </IonButton>
                </div>
              );
            })}
          </div>
        </div>
      </div>
      {/*  */}
      <CorrectAnswerToast isOpen={isOpenCorrectAnswer} dismiss={() => setIsOpenCorrectAnswer(false)} />
      {/*  */}
      <WrongAnswerToast isOpen={isOpenWrongAnswer} dismiss={() => setIsOpenWrongAnswer(false)} />
      {/*  */}
      <AudioControls audio_src={question_meta.sound} />
    </>
  );
};

function shuffleArray(in_array: string[]) {
  for (let i = in_array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = in_array[i];
    in_array[i] = in_array[j];
    in_array[j] = temp;
  }
  return in_array;
}

export default ListeningPracticeQuestionCard;
