import { IonButton, IonButtons, IonContent, IonIcon, IonModal, IonPage, IonToolbar, useIonRouter } from '@ionic/react';
import './style.css';
import {
  chevronBack,
  chevronForward,
  closeOutline,
  heart,
  heartOutline,
  playOutline,
  volumeHighOutline
} from 'ionicons/icons';
import { useEffect, useRef, useState } from 'react';
import { listLessonContent } from '../../../public_data';
import { useParams } from 'react-router';
import { getFavLessonConnectivesLink, getLessonConnectivesLink } from '../getLessonConnectivesLink';
import { LoadingScreen } from '../../../components/LoadingScreen';
import { AudioControls } from '../../LessonWord/AudioControls';
import { useGlobalAudioPlayer } from 'react-use-audio-player';
import { useMyIonFavorite } from '../../../contexts/MyIonFavorite';
import RemoveFavoritePrompt from '../../../components/RemoveFavoritePrompt';
//
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

const ConnectivesPage: React.FC = () => {
  let [loading, setLoading] = useState<boolean>(true);
  let [all_words_length, setAllWordsLength] = useState<number>(0);
  let [show_word, setShowWord] = useState({ word: '', word_c: '', sample_e: '', sample_c: '', sound: '' });
  let [cat_name, setCatName] = useState<string>('');
  let [fav_active, setFavActive] = useState<boolean>(false);
  let { playing, play: sound_play } = useGlobalAudioPlayer();

  let router = useIonRouter();
  let { lesson_idx, cat_idx, word_idx } = useParams<{ lesson_idx: string; cat_idx: string; word_idx: string }>();
  let i_lesson_idx = parseInt(lesson_idx);
  let i_cat_idx = parseInt(cat_idx);
  let i_word_idx = parseInt(word_idx);
  const [isOpen, setIsOpen] = useState(false);

  const [open_remove_modal, setOpenRemoveModal] = useState(false);
  const modal = useRef<HTMLIonModalElement>(null);

  // const lesson_vocab_address = `/lesson_word_page/v/${lesson_idx}/${cat_idx}/${word_idx}`;
  let [favorite_address, setFavoriteAddress] = useState(getFavLessonConnectivesLink(lesson_idx, cat_idx, word_idx));

  function dismiss() {
    setOpenRemoveModal(false);
  }

  function handleUserClickPrev() {
    if (i_word_idx > 0) {
      router.push(getLessonConnectivesLink(lesson_idx, cat_idx, (i_word_idx - 1).toString()));
    }
  }

  function handleUserClickNext() {
    if (i_word_idx < all_words_length - 1) {
      router.push(getLessonConnectivesLink(lesson_idx, cat_idx, (i_word_idx + 1).toString()));
    }
  }

  const { myIonStoreAddFavoriteConnectives, myIonStoreRemoveFavoriteConnectives, myIonStoreFindInFavoriteConnectives } =
    useMyIonFavorite();

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

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

  function handleUserRemoveFavorite() {
    setOpenRemoveModal(true);
  }

  useEffect(() => {
    (async () => {
      let lesson_content = await listLessonContent();
      let word_cat = lesson_content[i_lesson_idx].content[i_cat_idx];
      setCatName(word_cat['cat_name']);
      let all_words = lesson_content[i_lesson_idx].content[i_cat_idx].content;
      setAllWordsLength(all_words.length);
      let show_word = lesson_content[i_lesson_idx].content[i_cat_idx].content[i_word_idx];
      setShowWord(show_word);

      console.log({ t: lesson_content[i_lesson_idx].content[i_cat_idx].content[i_word_idx] });

      setFavoriteAddress(getFavLessonConnectivesLink(lesson_idx, cat_idx, word_idx));

      isInFavorite(getFavLessonConnectivesLink(lesson_idx, cat_idx, word_idx));
      // console.log({ in_fav, favorite_address });

      setLoading(false);
    })();
  }, [i_lesson_idx, i_cat_idx, i_word_idx]);

  if (loading) 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 {i_word_idx + 1}/{all_words_length}
              </div>
            </div>
            {/* <LessonContainer name='Tab 1 page' /> */}
            <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_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: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                gap: '1rem',
                width: '100%'

                //
              }}
            >
              <div>
                <IonButton
                  shape='round'
                  fill='clear'
                  color='dark'
                  size='large'
                  onClick={handleUserClickPrev}
                  disabled={i_word_idx + 1 <= 1}
                >
                  <IonIcon slot='icon-only' 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: show_word.word }}></div>
                <div style={{ fontSize: '1.6rem' }} dangerouslySetInnerHTML={{ __html: show_word.word_c }}></div>
              </div>
              {/*  */}
              <div>
                <IonButton
                  shape='round'
                  fill='clear'
                  color='dark'
                  size='large'
                  onClick={handleUserClickNext}
                  disabled={i_word_idx + 1 >= all_words_length}
                >
                  <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={() => sound_play()}>
                    <IonIcon slot='icon-only' icon={playing ? playOutline : volumeHighOutline}></IonIcon>
                  </IonButton>
                </div>
                {/* <div style={{ fontSize: '1rem' }} dangerouslySetInnerHTML={{ __html: show_word.sample_e }}></div> */}
                <div style={{ fontSize: '1rem' }}>
                  <Markdown remarkPlugins={[remarkGfm]}>{show_word.sample_e}</Markdown>
                </div>
              </div>

              <div
                style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', margin: '1rem 1rem 0 1rem' }}
              >
                <div style={{ fontSize: '1.1rem' }}>
                  <Markdown remarkPlugins={[remarkGfm]}>{show_word.sample_c}</Markdown>
                </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} />

      {/*  */}
      <AudioControls audio_src={show_word.sound} />
    </>
  );
};

export default ConnectivesPage;
