import React, {useCallback, useState} from 'react';
import {useTranslation} from 'react-i18next';
import {GiphyContent, GiphyGridView, GiphyMedia} from '@giphy/react-native-sdk';
import Animated from 'react-native-reanimated';
import {InputSearch} from '@components';
import {GIPHY_CONFIG} from '@config/giphy';
import {useDebounce} from '@hooks/useDebounce';
import {useGiphyDialogAnimatedStyle} from '@modules/chats/screens/ChatMessages/components/ChatFooter/components/AnimationProvider';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  onMediaSelect: (media: GiphyMedia) => void;
}
export function GiphyDialog({onMediaSelect}: Props) {
  const [search, setSearch] = useState('');
  const animatedStyle = useGiphyDialogAnimatedStyle();
  const {theme} = useTheme();
  const {t} = useTranslation();
  const debouncedSearch = useDebounce(search, 500);

  const onChangeSearch = useCallback((text: string) => {
    setSearch(text);
  }, []);

  return (
    <Animated.View
      style={[
        animatedStyle,
        styles.container,
        {backgroundColor: theme.background.layout.tertiary},
      ]}>
      <InputSearch
        value={search}
        placeholder={t('general.search')}
        style={styles.inputContainer}
        variant="disabled"
        onChangeText={onChangeSearch}
      />
      <GiphyGridView
        cellPadding={2}
        content={
          debouncedSearch
            ? GiphyContent.search({
                searchQuery: debouncedSearch,
                mediaType: 'gif',
                rating: GIPHY_CONFIG.rating,
              })
            : GiphyContent.trendingGifs({
                rating: GIPHY_CONFIG.rating,
              })
        }
        style={styles.giphyGridView}
        spanCount={3}
        onMediaSelect={e => {
          onMediaSelect(e.nativeEvent.media);
        }}
      />
    </Animated.View>
  );
}
