import React, {memo, useEffect, useMemo} from 'react';
import {Keyboard} from 'react-native';
import {
  GiphyDialog,
  GiphyDialogEvent,
  GiphyMedia,
} from '@giphy/react-native-sdk';
import {IconGif} from '@tabler/icons-react-native';
import {useNewPost} from '@components/_custom/NewPost/hooks/useNewPost';

import {BaseButton} from '../BaseButton';

interface Props {
  hasMaxSize: boolean;
}

function GifDisplayer({hasMaxSize}: Props) {
  const {setGif, files, videos, images, isLoading, hasPoll, gif, editor, post} =
    useNewPost();
  const requestEdit = !!post?._links?.requestEdit;

  const attachments = useMemo(() => images.concat(videos), [images, videos]);

  const disabled =
    hasMaxSize ||
    !!attachments.length ||
    !!files.length ||
    !!gif ||
    hasPoll ||
    isLoading ||
    requestEdit;

  const onOpenDisplayer = () => {
    try {
      editor.blur();
      Keyboard.dismiss();
      GiphyDialog.show();
    } catch (error) {
      // No need to handle errors, but is required to catch them to avoid component crashed
    }
    return null;
  };

  useEffect(() => {
    const mediaSelectedListener = GiphyDialog.addListener(
      GiphyDialogEvent.MediaSelected,
      ({media}: {media: GiphyMedia}) => {
        setGif(media);
        try {
          GiphyDialog.hide();
        } catch (error) {
          // No need to handle errors, but is required to catch them to avoid component crashed
        }
      },
    );
    return () => {
      mediaSelectedListener.remove();
    };
  }, [setGif]);

  return (
    <BaseButton Icon={IconGif} onPress={onOpenDisplayer} disabled={disabled} />
  );
}

export default memo(GifDisplayer);
