import { useEffect, useState } from 'react';
import { IonButton, IonContent, IonHeader, IonIcon, IonPage, IonTitle, IonToolbar, useIonRouter } from '@ionic/react';
import { heart } from 'ionicons/icons';

import { useMyIonMetric } from '../../contexts/MyIonMetric';
import { LoadingScreen } from '../../components/LoadingScreen';
import NoFavoriteConnectivesModal from '../../components/NoFavoriteVocabModal';
import GeniusProgressBar from '../../components/GeniusProgressBar';
import HardWorkerProgressBar from '../../components/HardWorkerProgressBar';
import AttentiveEarsProgressBar from '../../components/AttentiveEarsProgressBar';
import MatchmakingProgressBar from '../../components/MatchmakingProgressBar';
import ConnectivesConquerorProgressBar from '../../components/ConnectivesConquerorProgressBar';
import {
  ATTENTIVE_EARS_STAGES as ATTENTIVE_EAR_STAGES,
  COLOR_TEXT,
  CONNECTIVE_CONQUEROR_STAGES,
  DEBUG,
  FAVORITE_LINK,
  GENIUS_STAGES,
  HARDWORKER_STAGES,
  MATCHMAKING_STAGES,
  RECORD_LINK
} from '../../constants';
import { useMyIonFavorite } from '../../contexts/MyIonFavorite';
import NoFavoriteVocabModal from '../../components/NoFavoriteConnectivesModal';

import { useAppStateContext } from '../../contexts/AppState';
import CongratulationAchievementModal from '../../components/Modal/CongratulationAchievement';

import './style.css';
import { useFullmarkCount } from '../../contexts/MyIonMetric/FullmarkCount';
import {
  ListeningPracticeTimeSpentProvider,
  useListeningPracticeTimeSpent
} from '../../contexts/MyIonMetric/ListeningPracticeTimeSpent';
import { useConnectivesRevisionCorrectCount } from '../../contexts/MyIonMetric/ConnectivesRevisionCorrectCount';
import { useMatchingFrenzyCorrectCount } from '../../contexts/MyIonMetric/MatchingFrenzyCorrectCount';
import { useAppUseTime } from '../../contexts/MyIonMetric/AppUseTime';
import CongratListeningProgress from '../../components/Modal/Congratulation/ListeningProgress';
import CongratHelloworld from '../../components/Modal/Congratulation/Helloworld';
import CongratMatchmaking from '../../components/Modal/Congratulation/Matchmaking';
import CongratConnectiveConqueror from '../../components/Modal/Congratulation/ConnectiveConqueror';
import CongratGenius from '../../components/Modal/Congratulation/Genius';
import CongratHardworker from '../../components/Modal/Congratulation/Hardworker';

const MyAchievementPage: React.FC = () => {
  const [loading, setLoading] = useState(true);

  //
  const router = useIonRouter();
  const [full_mark_count, setFullMarkCount] = useState(0);
  const [hard_worker_progress, setHardWorkerProgress] = useState(0);
  const [listening_practice_progress, setListeningPracticeProgress] = useState(0);
  const [matching_frenzy_progress, setMatchingFrenzyProgress] = useState(0);
  const [app_use_time, setAppUseTime] = useState<number>(0);
  const [connectives_revision_progress, setConnectivesRevisionProgress] = useState(0);
  const [num_fav_vocab, setnumFavVocab] = useState(0);
  const [num_fav_connectives, setnumFavConnectives] = useState(0);
  const [openNoFavVocab, setOpenNoFavVocab] = useState(false);
  const [openNoFavConnectives, setOpenNoFavConnectives] = useState(false);
  const { myIonStoreLoadFavoriteVocabulary, myIonStoreLoadFavoriteConnectives } = useMyIonFavorite();

  const [openedCongraFullmarkTimes, setOpenedCongraFullmarkTimes] = useState<boolean>(false);
  const [congra_msg, setCongraMsg] = useState<string>('');
  const [openCongratListeningProgress, setOpenCongratListeningProgress] = useState(false);

  const { myIonMetricGetAppUseTime } = useAppUseTime();

  const { myIonMetricGetListeningPracticeTimeSpent } = useListeningPracticeTimeSpent();
  const { myIonMetricGetConnectivesRevisionCorrectCount } = useConnectivesRevisionCorrectCount();
  const { myIonMetricGetMatchingFrenzyCorrectCount } = useMatchingFrenzyCorrectCount();

  const {
    //
    myIonMetricGetFullMarkCount,
    myIonMetricGetFullMarkIgnore
  } = useFullmarkCount();

  const {
    //
    Helloworld,
    myIonMetricGetListeningPracticeProgressIgnore,
    myIonMetricSetListeningPracticeProgressIgnore
  } = useListeningPracticeTimeSpent();

  const [count_prompted, setCountPrompted] = useState(0);

  //
  async function promptFullmark(count_to_prompt: number) {
    if (count_to_prompt == (await myIonMetricGetFullMarkIgnore()).count) return;
    setCountPrompted(count_to_prompt);
    setCongraMsg('You scored full marks ' + count_to_prompt + ' times.');
    setOpenedCongraFullmarkTimes(true);
  }

  function checkPromptCongratulationFullMark(full_mark_count: number) {
    const prompt_list = [10, 50, 100, 200, 700, 1000];
    const b_prompt_list = Array(prompt_list.length).fill(false);

    for (let i = 0; i < prompt_list.length; i++) {
      if (full_mark_count > prompt_list[i]) {
        b_prompt_list[i] = true;
      }
    }

    let lastTrueIndex = -1;
    for (let i = b_prompt_list.length - 1; i >= 0; i--) {
      if (b_prompt_list[i]) {
        lastTrueIndex = i;
        break;
      }
    }

    if (lastTrueIndex == -1) {
      console.log('prompt ignored');
    } else {
      promptFullmark(prompt_list[lastTrueIndex]);
    }
  }

  //
  function dismissListeningPracticeCongratulation() {
    myIonMetricSetListeningPracticeProgressIgnore(count_prompted);
  }

  //
  async function promptMatchmaking(count_to_prompt: number) {
    if (count_to_prompt == (await myIonMetricGetFullMarkIgnore()).count) return;
    setCountPrompted(count_to_prompt);
    setCongraMsg('You scored match making ' + count_to_prompt + ' times.');
    setOpenedCongraFullmarkTimes(true);
  }

  function checkPromptMatchmaking(full_mark_count: number) {
    const prompt_list = [10, 50, 100, 200, 700, 1000];
    const b_prompt_list = Array(prompt_list.length).fill(false);

    for (let i = 0; i < prompt_list.length; i++) {
      if (full_mark_count > prompt_list[i]) {
        b_prompt_list[i] = true;
      }
    }

    let lastTrueIndex = -1;
    for (let i = b_prompt_list.length - 1; i >= 0; i--) {
      if (b_prompt_list[i]) {
        lastTrueIndex = i;
        break;
      }
    }

    if (lastTrueIndex == -1) {
      console.log('prompt ignored');
    } else {
      promptMatchmaking(prompt_list[lastTrueIndex]);
    }
  }

  let { tab_active, setTabActive } = useAppStateContext();
  useEffect(() => {
    if (full_mark_count > 0) {
      checkPromptCongratulationFullMark(full_mark_count);
    }
  }, [tab_active, full_mark_count]);

  useEffect(() => {}, [tab_active, matching_frenzy_progress]);
  useEffect(() => {
    if (connectives_revision_progress > 0) checkPromptMatchmaking(connectives_revision_progress);
  }, [tab_active, connectives_revision_progress]);
  useEffect(() => {}, [tab_active, app_use_time]);

  const { setDisableUserTap } = useAppStateContext();

  useEffect(() => {
    (async () => {
      let { time_spent_s } = await myIonMetricGetAppUseTime();
      setHardWorkerProgress(time_spent_s);

      const { count: full_mark_count } = await myIonMetricGetFullMarkCount();
      setFullMarkCount(full_mark_count);

      const { count: matching_frenzy_correct_count } = await myIonMetricGetMatchingFrenzyCorrectCount();
      setMatchingFrenzyProgress(matching_frenzy_correct_count);

      const { count: connectives_revision_correct_count } = await myIonMetricGetConnectivesRevisionCorrectCount();
      setConnectivesRevisionProgress(connectives_revision_correct_count);

      setLoading(false);
    })();

    (async () => {
      let temp_fav_list = await myIonStoreLoadFavoriteVocabulary();
      setnumFavVocab(temp_fav_list.length);

      let temp_fav_c_list = await myIonStoreLoadFavoriteConnectives();
      setnumFavConnectives(temp_fav_c_list.length);
    })();

    setTabActive(RECORD_LINK);

    (async () => {
      let temp = await myIonMetricGetListeningPracticeTimeSpent();
      setListeningPracticeProgress(temp.time_spent_s);
    })();

    setDisableUserTap(false);
  }, []);

  if (loading) return <LoadingScreen />;

  return (
    <>
      <IonPage>
        <IonHeader className='ion-no-border'>
          <IonToolbar>
            <IonTitle>{'My Achievement'}</IonTitle>
          </IonToolbar>
        </IonHeader>
        <IonContent fullscreen>
          <IonHeader collapse='condense'>
            <IonToolbar>
              <IonTitle size='large' style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <div style={{ color: COLOR_TEXT }}>{'My Achievement'}</div>
              </IonTitle>
            </IonToolbar>
          </IonHeader>
          <div
            style={{
              marginLeft: '1rem',
              marginRight: '1rem',
              marginBottom: '1rem',
              //
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              color: COLOR_TEXT
            }}
          >
            <div
              style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'flex-start',
                width: '100%'
              }}
            >
              <div style={{ marginTop: '2rem', width: '100%' }}>
                <div style={{ fontSize: '1.2rem' }}>Genius</div>
                <div style={{ fontSize: '0.8rem' }}>No of times getting the perfect score</div>
                <div style={{ fontSize: '0.8rem' }}>
                  {GENIUS_STAGES.join(' / ')} {DEBUG ? <span className='debug'>({full_mark_count})</span> : ''}
                </div>

                <div style={{ marginTop: '0.1rem' }}>
                  <div style={{ fontSize: '0.8rem' }}> </div>
                  <div style={{ marginTop: '0.2rem' }}>
                    <GeniusProgressBar value={full_mark_count} range_list={[10, 50, 100, 300, 700, 1000]} />
                  </div>
                </div>
              </div>
              <div style={{ marginTop: '2rem', width: '100%' }}>
                <div style={{ fontSize: '1.2rem', color: COLOR_TEXT }}>Hard worker</div>
                <div style={{ fontSize: '0.8rem' }}>Overall Practice duration (In mint.res)</div>
                <div style={{ fontSize: '0.8rem' }}>
                  {HARDWORKER_STAGES.join(' / ')} min{' '}
                  {DEBUG ? <span className='debug'>({(hard_worker_progress / 60).toFixed(3)})</span> : ''}
                </div>

                <div style={{ marginTop: '0.1rem' }}>
                  <div style={{ fontSize: '0.8rem' }}> </div>
                  <div style={{ marginTop: '0.2rem' }}>
                    <HardWorkerProgressBar
                      value={Math.floor(hard_worker_progress / 60)}
                      range_list={[5, 50, 100, 500, 1000, 1500, 3000]}
                    />
                  </div>
                </div>
              </div>
              <div style={{ marginTop: '2rem', width: '100%' }}>
                <div style={{ fontSize: '1.2rem', color: COLOR_TEXT }}>Attentive Ears</div>
                <div style={{ fontSize: '0.8rem' }}>Duration of listening Track completed</div>
                <div style={{ fontSize: '0.8rem' }}>
                  {ATTENTIVE_EAR_STAGES.join(' / ')} min
                  {DEBUG ? <span className='debug'>({(listening_practice_progress / 60).toFixed(3)})</span> : ''}
                </div>

                <div style={{ marginTop: '0.1rem' }}>
                  <div style={{ fontSize: '0.8rem' }}> </div>
                  <div style={{ marginTop: '0.2rem' }}>
                    <AttentiveEarsProgressBar
                      value={Math.floor(listening_practice_progress / 60)}
                      range_list={ATTENTIVE_EAR_STAGES}
                    />
                  </div>
                </div>
              </div>
              <div style={{ marginTop: '2rem', width: '100%' }}>
                <div style={{ fontSize: '1.2rem', color: COLOR_TEXT }}>Matchmaking</div>
                <div style={{ fontSize: '0.8rem' }}>No of correct matches mode</div>
                <div style={{ fontSize: '0.8rem' }}>
                  {MATCHMAKING_STAGES.join(' / ')}
                  {DEBUG ? <span className='debug'>({(matching_frenzy_progress / 60).toFixed(3)})</span> : ''}
                </div>

                <div style={{ marginTop: '0.1rem' }}>
                  <div style={{ fontSize: '0.8rem' }}> </div>
                  <div style={{ marginTop: '0.2rem' }}>
                    <MatchmakingProgressBar
                      value={matching_frenzy_progress}
                      range_list={[30, 100, 250, 500, 1500, 3000, 8000]}
                    />
                  </div>
                </div>
              </div>
              <div style={{ marginTop: '2rem', width: '100%' }}>
                <div style={{ fontSize: '1.2rem', color: COLOR_TEXT }}>Connectives Conqueror</div>
                <div style={{ fontSize: '0.8rem' }}>No of completed connective exercises</div>
                <div style={{ fontSize: '0.8rem' }}>
                  {CONNECTIVE_CONQUEROR_STAGES.join(' / ')}{' '}
                  {DEBUG ? <span className='debug'>({connectives_revision_progress})</span> : ''}
                </div>

                <div style={{ marginTop: '0.1rem' }}>
                  <div style={{ fontSize: '0.8rem' }}> </div>
                  <div style={{ marginTop: '0.2rem' }}>
                    <ConnectivesConquerorProgressBar
                      value={connectives_revision_progress}
                      range_list={CONNECTIVE_CONQUEROR_STAGES}
                    />
                  </div>
                </div>
              </div>
            </div>

            <div style={{ borderTop: '1px solid #ccc', width: '100%', marginTop: '1rem' }}></div>
            <div
              style={{
                marginTop: '1rem',
                width: '100%',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'space-between'
                //
              }}
            >
              {/*  */}
              <IonButton
                fill='outline'
                color='dark'
                onClick={() => (num_fav_vocab > 0 ? router.push(`${FAVORITE_LINK}/v`) : setOpenNoFavVocab(true))}
              >
                <div
                  style={{
                    padding: '1rem',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    gap: '1rem'
                  }}
                >
                  <IonIcon icon={heart} color='danger' size='large'></IonIcon>
                  <div>
                    {'Liked Vocabulary'} <span style={{ fontWeight: 'bold' }}>({num_fav_vocab || 0})</span>
                  </div>
                </div>
              </IonButton>
              {/*  */}
              <IonButton
                fill='outline'
                color='dark'
                onClick={() =>
                  num_fav_connectives > 0 ? router.push(`${FAVORITE_LINK}/c`) : setOpenNoFavConnectives(true)
                }
              >
                <div
                  style={{
                    padding: '1rem',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    gap: '1rem'
                  }}
                >
                  <IonIcon icon={heart} color='danger' size='large'></IonIcon>
                  <div>
                    {'Liked Connectives'} <span style={{ fontWeight: 'bold' }}>({num_fav_connectives || 0})</span>
                  </div>
                </div>
              </IonButton>
              {/*  */}
            </div>
          </div>
        </IonContent>
      </IonPage>
      {/*  */}
      <NoFavoriteVocabModal open={openNoFavVocab} setOpen={setOpenNoFavVocab} />
      <NoFavoriteConnectivesModal open={openNoFavConnectives} setOpen={setOpenNoFavConnectives} />
      {/*  */}
      {/* 
      <CongratulationAchievementModal
        count_prompted={count_prompted}
        opened={openedCongraFullmarkTimes}
        setOpened={setOpenedCongraFullmarkTimes}
        message={congra_msg}
      /> 
      */}
      {/*  */}
      {/* <CongratHelloworld /> */}
      <CongratGenius />
      <CongratHardworker />
      <CongratListeningProgress />
      <CongratMatchmaking />
      <CongratConnectiveConqueror />
    </>
  );
};

export default MyAchievementPage;
