import React, { useRef, useEffect, useState, useContext } from 'react';
import { useField } from '@unform/core';
import AppContext from '../AppProvider/AppContext';
import { YoutubeService } from '../../services/youtube.service';
import { Input } from '../Input/web';
import { LoaderIcon } from '../LoaderIcon/web';
import Style from './InputYoutube.style';

interface IPropsInputYoutube {
   name: string;
   theme?: string;
   title?: string;
   onInvalidUrl?: any;
   keyYTB?: string;
}

export const InputYoutube: React.FunctionComponent<IPropsInputYoutube> = (props: IPropsInputYoutube) => {
   const { keyYTB } = useContext(AppContext);
   const { name, title, theme: themeInput, onInvalidUrl, keyYTB: keyYTBComponent, ...rest } = props;

   const [error, setError] = useState(false);
   const [invalidVideo, setInvalidVideo] = useState('');
   const [searching, setSearching] = useState(false);
   const [videoInfo, setVideoInfo] = useState({} as any);
   // Unform
   const { defaultValue = '', clearError } = useField(name);

   const timeOut = useRef<any>();

   // onEnter
   const onChange = async (e): Promise<void> => {
      e.persist();

      const value = e.target.value;

      clearError();

      setInvalidVideo('');
      setSearching(true);
      clearTimeout(timeOut.current);

      timeOut.current = setTimeout(async () => {
         if (value.length > 0) {
            const data = await YoutubeService(e.target.value, keyYTBComponent ?? keyYTB).catch((err) => {
               if (!err.response) setInvalidVideo('Erro ao verificar id do video, verifique sua internet.');
               if (err.response) setInvalidVideo('Erro ao verificar id do video, estamos verificando.');
               /**
                * TODO: enviar response do erro para logs
                */
               return null;
            });

            if (!data) {
               setError(!data);
               if (onInvalidUrl) {
                  onInvalidUrl();
               }
            } else {
               setVideoInfo(data);
               setError(false);
            }
         }

         setSearching(false);
      }, 300);
   };

   useEffect(() => {
      clearError();

      if (defaultValue.length > 0) {
         YoutubeService(defaultValue, keyYTBComponent ?? keyYTB)
            .then((data) => {
               if (!data) {
                  setError(!data);
                  if (onInvalidUrl) {
                     onInvalidUrl();
                  }
               } else {
                  setVideoInfo(data);
                  setError(false);
               }
            })
            .catch(() => {
               setError(true);
            });
      }
   }, []);

   return (
      <Style>
         <Input
            name={name}
            title={title}
            theme="gray"
            data-cy={name}
            prefix={
               <>
                  <i className="fab fa-youtube text-danger" />
               </>
            }
            onInput={(e) => {
               onChange(e);
            }}
            {...rest}
            suffix={<>{searching && <LoaderIcon size={24} />}</>}
         />

         {invalidVideo && (
            <div className="error-input" data-testid="input-error">
               {invalidVideo}
            </div>
         )}

         {!error && !!videoInfo.title && (
            <div className="youtube-container">
               <div className="img-container">
                  <img src={videoInfo.thumbnail} alt={videoInfo.title} data-cy="yt-img" />
               </div>

               <div className="video-info">
                  <div className="youtube-url">YOUTUBE.COM</div>
                  <div className="youtube-title" data-cy="yt-title">
                     {videoInfo.title}
                  </div>
                  <div className="youtube-description" data-cy="yt-description">
                     {videoInfo.description}
                  </div>
               </div>
            </div>
         )}
      </Style>
   );
};
