import { useState, useEffect, useCallback } from 'react';

import { useTranslation } from 'react-i18next';

import { GifsResult } from '@giphy/js-fetch-api';
import type { IGif } from '@giphy/js-types';

import { useDebounce } from '@material-hu/hooks/useDebounce';

import { getTrendingGifs, searchGifs } from 'src/services/attachments';

const GIF_SELECTION_DELAY = 500;
const GIF_RATING = 'pg';
const GIF_LIMIT = 10;

type UseGifSearchProps = {
  onGifSelection?: (gif: IGif) => void;
  onClose?: () => void;
};

export const useGifSearch = ({
  onGifSelection,
  onClose,
}: UseGifSearchProps = {}) => {
  const [query, setQuery] = useState('');
  const [isGifSelectable, setIsGifSelectable] = useState(false);
  const { t } = useTranslation('attachments');

  const searchTerm = useDebounce(query);

  const fetchGifs = useCallback(
    (offset: number) => {
      const fetchRequest = searchTerm
        ? searchGifs(searchTerm, {
            offset,
            limit: GIF_LIMIT,
            rating: GIF_RATING,
          })
        : getTrendingGifs({ offset, limit: GIF_LIMIT, rating: GIF_RATING });

      return fetchRequest.catch(() => {
        const emptyGifsResult: GifsResult = {
          meta: {
            status: 200,
            msg: 'OK',
            response_id: 'error',
          },
          data: [],
          pagination: {
            total_count: 0,
            count: 0,
            offset: 0,
          },
        };
        return emptyGifsResult;
      });
    },
    [searchTerm],
  );

  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (!isGifSelectable) {
      timer = setTimeout(() => {
        setIsGifSelectable(true);
      }, GIF_SELECTION_DELAY);
    }
    return () => clearTimeout(timer);
  }, [isGifSelectable]);

  const handleSelectGif = (gif: IGif, e: React.SyntheticEvent<HTMLElement>) => {
    e.preventDefault();
    if (!isGifSelectable) return;

    setIsGifSelectable(false);
    onGifSelection?.(gif);
    onClose?.();
  };

  const handleQueryChange = (value: any) => setQuery(value);

  const resetQuery = () => setQuery('');

  return {
    query,
    searchTerm,
    isGifSelectable,
    fetchGifs,
    handleSelectGif,
    handleQueryChange,
    resetQuery,
    t,
  };
};

export default useGifSearch;
