import { IonButton, IonButtons, IonIcon, IonModal, IonToast, useIonRouter } from '@ionic/react';
import { IonContent, IonPage, IonToolbar } from '@ionic/react';
import './style.css';
import {
  chevronBack,
  chevronForward,
  closeCircleOutline,
  closeOutline,
  heart,
  heartOutline,
  play,
  volumeHighOutline
} from 'ionicons/icons';

import { useEffect, useRef, useState } from 'react';
import { useParams } from 'react-router';
import { getFavLessonConnectivesLink } from '../getLessonConnectivesLink';
import { RECORD_LINK } from '../../../constants';
import { useGlobalAudioPlayer } from 'react-use-audio-player';
//
import { useMyIonStore } from '../../../contexts/MyIonStore';
import ILesson from '../../../interfaces/ILesson';
import ILessonCategory from '../../../interfaces/ILessonCategory';
import IWordCard from '../../../interfaces/IWordCard';
import { LoadingScreen } from '../../../components/LoadingScreen';
import { useMyIonFavorite } from '../../../contexts/MyIonFavorite';
import RemoveFavoritePrompt from '../../../components/RemoveFavoritePrompt';

// import { StoreContext, useMyIonStore } from '../../contexts/store';
//

const ConnectivesWordPage: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const router = useIonRouter();
  let [fav_cursor, setFavCursor] = useState<number>(0);
  const [open_remove_modal, setOpenRemoveModal] = useState(false);

  const modal = useRef<HTMLIonModalElement>(null);
  const { lesson_idx, cat_idx, word_idx } = useParams<{ lesson_idx: string; cat_idx: string; word_idx: string }>();

  const [lesson_info, setLessonInfo] = useState<ILesson | undefined>(undefined);
  const [cat_info, setCatInfo] = useState<ILessonCategory | undefined>(undefined);
  const [word_info, setWordInfo] = useState<IWordCard | undefined>(undefined);

  const { play: play_word, playing } = useGlobalAudioPlayer();
  const {
    myIonStoreAddFavoriteConnectives,
    myIonStoreRemoveFavoriteConnectives,
    myIonStoreFindInFavoriteConnectives,
    myIonStoreLoadFavoriteConnectives
  } = useMyIonFavorite();

  let [favorite_address, setFavoriteAddress] = useState(getFavLessonConnectivesLink(lesson_idx, cat_idx, word_idx));

  function dismiss() {
    setOpenRemoveModal(false);
  }
  const [isOpen, setIsOpen] = useState(false);

  let { lesson_contents } = useMyIonStore();

  useEffect(() => {
    // NOTES: lesson_content == [] during loading
    if (lesson_contents.length > 0) {
      let lesson_content: ILesson = lesson_contents[parseInt(lesson_idx)];
      let category_content: ILessonCategory = lesson_content.content[parseInt(cat_idx)];
      let word_content: IWordCard = category_content.content[parseInt(word_idx)];

      setLessonInfo(lesson_content);
      setCatInfo(category_content);
      setWordInfo(word_content);

      setLoading(false);
    }
  }, [lesson_contents, word_idx]);

  let [in_fav, setInFav] = useState(false);
  const isInFavorite = async (string_to_search: string) => {
    let result = await myIonStoreFindInFavoriteConnectives(string_to_search);
    setInFav(result);
  };

  const addToFavorite = async (string_to_add: string) => {
    await myIonStoreAddFavoriteConnectives(string_to_add);
    await isInFavorite(string_to_add);
  };

  function handleUserRemoveFavorite() {
    setOpenRemoveModal(true);
  }

  const removeFromFavorite = async (string_to_remove: string) => {
    let list_before_remove = await myIonStoreLoadFavoriteConnectives();

    await myIonStoreRemoveFavoriteConnectives(string_to_remove);

    let temp_list = await myIonStoreLoadFavoriteConnectives();
    setFavList(temp_list);

    const deleteFirstElement = () => fav_cursor == 0;
    const deleteLastElement = () => fav_cursor == list_before_remove.length - 1;
    const lastElementNewList = temp_list[temp_list.length - 1];
    const firstElementNewList = temp_list[0];
    const samePosElementNewList = temp_list[fav_cursor];

    if (deleteFirstElement()) {
      if (!firstElementNewList) {
        router.push(RECORD_LINK, undefined, 'replace');
      } else {
        router.push(`${firstElementNewList}`, undefined, 'replace');
      }
    } else if (deleteLastElement()) {
      if (!lastElementNewList) {
        router.push(RECORD_LINK, undefined, 'replace');
      } else {
        router.push(`${lastElementNewList}`, undefined, 'replace');
      }
    } else {
      if (!samePosElementNewList) {
        router.push(RECORD_LINK, undefined, 'replace');
      } else {
        router.push(`${samePosElementNewList}`, undefined, 'replace');
      }
    }

    await isInFavorite(string_to_remove);
  };

  let [fav_list, setFavList] = useState<string[]>([]);

  const locateInFavCursor = (string_to_search: string) => setFavCursor(fav_list.indexOf(string_to_search) ?? 0);

  useEffect(() => {
    if (JSON.stringify(fav_list) === '[]') return;
    let temp = getFavLessonConnectivesLink(lesson_idx, cat_idx, word_idx);
    if (fav_list.length === 0) {
    } else {
      locateInFavCursor(temp);
    }
  }, [fav_list]);

  async function handleNextClick() {
    let next_fav_link = fav_cursor < fav_list.length - 1 ? fav_list[fav_cursor + 1] : fav_list[fav_cursor];

    let temp_fav_list = await myIonStoreLoadFavoriteConnectives();
    setFavList(temp_fav_list);

    router.push(next_fav_link, undefined, 'replace');
  }

  async function handlePrevClick() {
    let prev_fav_link = fav_cursor > 0 ? fav_list[fav_cursor - 1] : fav_list[fav_cursor];

    let temp_fav_list = await myIonStoreLoadFavoriteConnectives();
    setFavList(temp_fav_list);

    router.push(prev_fav_link, undefined, 'replace');
  }

  useEffect(() => {
    let temp_fav_address = getFavLessonConnectivesLink(lesson_idx, cat_idx, word_idx);
    setFavoriteAddress(temp_fav_address);
    isInFavorite(temp_fav_address);
  }, [lesson_idx, cat_idx, word_idx]);

  useEffect(() => {
    (async () => {
      let temp_fav_list = await myIonStoreLoadFavoriteConnectives();
      setFavList(temp_fav_list);
    })();
  }, []);

  // if (loading) return <>loading</>;
  // if (!word_info) return <>loading</>;
  if (!cat_info || !word_info) return <LoadingScreen />;

  return (
    <>
      <IonPage>
        <IonContent fullscreen>
          <div style={{ marginTop: '3rem', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                margin: '1rem 1rem',
                justifyContent: 'space-between'
              }}
            >
              <div>
                Part {fav_cursor + 1}/{fav_list.length}
              </div>
            </div>
            {/*  */}
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                width: '80vw'
              }}
            >
              <div
                style={{
                  flexGrow: 1,
                  display: 'inline-flex',
                  justifyContent: 'center',
                  fontSize: '1.3rem'
                }}
                dangerouslySetInnerHTML={{ __html: cat_info.cat_name }}
              ></div>
            </div>
            {/*  */}
            <div style={{ marginTop: '1rem' }}>
              <IonButton
                shape='round'
                color='danger'
                fill='clear'
                size='large'
                onClick={() => {
                  in_fav ? handleUserRemoveFavorite() : addToFavorite(favorite_address);
                }}
              >
                <IonIcon slot='icon-only' icon={in_fav ? heart : heartOutline}></IonIcon>
              </IonButton>
            </div>
            {/*  */}
            <div style={{ display: 'inline-flex', flexDirection: 'row', alignItems: 'center', gap: '1rem' }}>
              <div>
                <IonButton
                  size='large'
                  shape='round'
                  fill='clear'
                  onClick={handlePrevClick}
                  color={fav_cursor <= 0 ? 'medium' : 'dark'}
                  disabled={fav_cursor <= 0}
                >
                  <IonIcon slot='icon-only' size='large' icon={chevronBack}></IonIcon>
                </IonButton>
              </div>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  gap: '0.5rem',
                  alignItems: 'center',
                  marginTop: '2rem',
                  fontSize: '1.3rem',
                  fontWeight: 'bold'
                }}
              >
                <div style={{ fontSize: '1.6rem' }} dangerouslySetInnerHTML={{ __html: word_info.word }}></div>
                <div style={{ fontSize: '1.6rem' }} dangerouslySetInnerHTML={{ __html: word_info.word_c }}></div>
              </div>
              <div>
                <IonButton
                  shape='round'
                  fill='clear'
                  size='large'
                  color={fav_cursor >= fav_list.length - 1 ? 'medium' : 'dark'}
                  disabled={fav_cursor >= fav_list.length - 1}
                  onClick={handleNextClick}
                >
                  <IonIcon slot='icon-only' icon={chevronForward}></IonIcon>
                </IonButton>
              </div>
            </div>
            {/*  */}
            <div style={{ marginTop: '2rem' }}>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'row',
                  gap: '1rem',
                  alignItems: 'center',
                  margin: '1rem 1rem 1rem'
                }}
              >
                <div>
                  <IonButton shape='round' fill='clear' color='dark' disabled={playing} onClick={() => play_word()}>
                    <IonIcon slot='icon-only' icon={playing ? play : volumeHighOutline}></IonIcon>
                  </IonButton>
                </div>
                <div style={{ fontSize: '1rem' }} dangerouslySetInnerHTML={{ __html: word_info.sample_e }}></div>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginTop: '1rem' }}>
                <div style={{ fontSize: '1.1rem' }} dangerouslySetInnerHTML={{ __html: word_info.sample_c }}></div>
              </div>
            </div>
            {/*  */}
          </div>
        </IonContent>
      </IonPage>
      {/*  */}

      <IonModal isOpen={open_remove_modal} id='example-modal' ref={modal}>
        <IonContent>
          <IonToolbar>
            <IonButtons slot='end'>
              <IonButton onClick={() => dismiss()} shape='round' fill='clear'>
                <IonIcon size='large' slot='icon-only' icon={closeOutline}></IonIcon>
              </IonButton>
            </IonButtons>
          </IonToolbar>
          <div style={{ marginTop: '2rem' }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <div>Are you sure to remove favorite ?</div>

              <div style={{ display: 'flex', flexDirection: 'row', gap: '1rem', marginTop: '1rem' }}>
                <div>
                  <IonButton color='dark' onClick={() => dismiss()} fill='outline'>
                    Cancel
                  </IonButton>
                </div>
                <div>
                  <IonButton
                    onClick={() => {
                      removeFromFavorite(getFavLessonConnectivesLink(lesson_idx, cat_idx, word_idx));
                      setIsOpen(true);
                      dismiss();
                    }}
                    fill='solid'
                    color='danger'
                  >
                    Remove
                  </IonButton>
                </div>
              </div>
            </div>
          </div>
        </IonContent>
      </IonModal>

      {/*  */}
      <RemoveFavoritePrompt open={isOpen} setIsOpen={setIsOpen} />
    </>
  );
};

export default ConnectivesWordPage;
