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

import { useEffect, useRef, useState } from 'react';
import { useParams } from 'react-router';
import { getFavLessonVocabularyLink, getLessonVocabularyLink } from '../../Lesson/getLessonWordLink';
import { AudioControls } from './AudioControls';
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 LessonWordPage: React.FC = () => {
  const router = useIonRouter();
  const [loading, setLoading] = useState(true);
  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 { myIonStoreAddFavoriteVocabulary, myIonStoreRemoveFavoriteVocabulary, myIonStoreFindInFavoriteVocabulary } =
    useMyIonFavorite();
  //
  // const lesson_vocab_address = `/lesson_word_page/v/${lesson_idx}/${cat_idx}/${word_idx}`;
  let [favorite_address, setFavoriteAddress] = useState(getFavLessonVocabularyLink(lesson_idx, cat_idx, word_idx));
  useEffect(() => {
    setFavoriteAddress(getFavLessonVocabularyLink(lesson_idx, cat_idx, word_idx));
  }, [lesson_idx, cat_idx, word_idx]);
  //

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

  useEffect(() => {
    console.log(cat_idx, word_idx, lesson_idx);
  }, []);

  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]);

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

  const addToFavorite = async (string_to_add: string) => {
    await myIonStoreAddFavoriteVocabulary(string_to_add);

    await isInFavorite(string_to_add);
    setInFav(!in_fav);
  };

  function handleUserRemoveFavorite() {
    setOpenRemoveModal(true);
  }

  const removeFromFavorite = async (string_to_remove: string) => {
    await myIonStoreRemoveFavoriteVocabulary(string_to_remove);
    await isInFavorite(string_to_remove);
  };

  useEffect(() => {
    (async () => {
      await isInFavorite(favorite_address);
    })();
  }, [lesson_idx, cat_idx, word_idx]);

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

  return (
    <>
      <IonPage>
        <IonContent fullscreen>
          <div style={{ marginTop: '3rem' }}>
            <div style={{ textAlign: 'center', fontSize: '1.2rem' }}>{cat_info.cat_name}</div>
          </div>
          <div style={{ marginTop: '1rem', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            {/* <LessonContainer name='Tab 1 page' /> */}
            <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
              <div>
                <IonButton
                  size='large'
                  shape='round'
                  fill='clear'
                  color={parseInt(word_idx) === 0 ? 'medium' : 'dark'}
                  disabled={parseInt(word_idx) === 0}
                  // href={getLessonVocabularyLink(lesson_idx, cat_idx, Math.max(0, parseInt(word_idx) - 1).toString())}
                  onClick={() => {
                    router.push(
                      getLessonVocabularyLink(lesson_idx, cat_idx, Math.max(0, parseInt(word_idx) - 1).toString())
                    );
                  }}
                >
                  <IonIcon slot='icon-only' size='large' icon={chevronBack}></IonIcon>
                </IonButton>
              </div>
              <div
                style={{
                  width: '66vw',
                  height: '66vw',
                  backgroundImage: `url(${word_info.image})`,
                  backgroundPosition: 'center',
                  backgroundSize: 'cover',
                  borderRadius: '0.5rem',
                  margin: '.5rem'
                }}
              ></div>
              <div>
                <IonButton
                  size='large'
                  shape='round'
                  fill='clear'
                  color={parseInt(word_idx) === cat_info.content.length - 1 ? 'medium' : 'dark'}
                  disabled={parseInt(word_idx) === cat_info.content.length - 1}
                  // href={getLessonVocabularyLink(
                  //   lesson_idx,
                  //   cat_idx,
                  //   Math.min(cat_info.content.length - 1, parseInt(word_idx) + 1).toString()
                  // )}
                  onClick={() => {
                    router.push(
                      getLessonVocabularyLink(
                        lesson_idx,
                        cat_idx,
                        Math.min(cat_info.content.length - 1, parseInt(word_idx) + 1).toString()
                      )
                    );
                  }}
                >
                  <IonIcon slot='icon-only' size='large' icon={chevronForward}></IonIcon>
                </IonButton>
              </div>
            </div>

            <div style={{ marginTop: '1rem' }}>
              <div
                style={{
                  width: '2rem',
                  height: '2rem',
                  display: 'inline-flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  borderRadius: '1rem',
                  backgroundColor: 'black',
                  color: 'white'
                }}
              >
                {parseInt(word_idx) + 1}
              </div>
            </div>

            <div>
              <div
                style={{ display: 'flex', flexDirection: 'row', gap: '1rem', alignItems: 'center', marginTop: '1rem' }}
              >
                <div>
                  <AudioControls audio_src={word_info.sound} />
                  <IonButton
                    size='large'
                    color='dark'
                    shape='round'
                    fill='clear'
                    disabled={playing}
                    onClick={() => (playing ? null : play_word())}
                  >
                    <IonIcon
                      size='large'
                      color='dark'
                      slot='icon-only'
                      icon={playing ? play : volumeHighOutline}
                    ></IonIcon>
                  </IonButton>
                </div>
                <div style={{ fontWeight: 'bold', fontSize: '1.5rem' }}>{word_info.word}</div>
                <div>
                  <IonButton
                    color='danger'
                    shape='round'
                    size='large'
                    fill='clear'
                    // id='open-modal'
                    onClick={() => {
                      in_fav ? handleUserRemoveFavorite() : addToFavorite(favorite_address);
                    }}
                  >
                    <IonIcon
                      size='large'
                      color='danger'
                      slot='icon-only'
                      icon={in_fav ? heart : heartOutline}
                    ></IonIcon>
                  </IonButton>
                </div>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginTop: '1rem' }}>
                <div style={{ fontWeight: 'bold', fontSize: '1.3rem' }}>{word_info.word_c}</div>
              </div>
            </div>

            <div
              style={{
                display: 'flex',
                flexDirection: 'column',
                gap: '0.5rem',
                alignItems: 'center',
                marginTop: '2rem'
              }}
            >
              <div dangerouslySetInnerHTML={{ __html: word_info.sample_e }}></div>
              <div dangerouslySetInnerHTML={{ __html: word_info.sample_c }}></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={close}></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(getFavLessonVocabularyLink(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 LessonWordPage;
