import { useCallback, useContext, useEffect, useState } from 'react' import { ChatContext } from '../contexts/chat_context' import { DenormalizedGiphyAttachmentResourceForCreate } from '../types/resources/denormalized_attachment_resource_for_create' interface GiphyGif { id: string url: string title: string images: { original: GiphyVariant fixed_height: GiphyVariant fixed_height_still: GiphyVariant fixed_height_downsampled: GiphyVariant fixed_width: GiphyVariant fixed_width_still: GiphyVariant fixed_width_downsampled: GiphyVariant } } interface GiphyVariant { url: string width: string height: string size: string frames: string } export function useGiphy(term: string = '') { const { giphyApiKey } = useContext(ChatContext) const [isSearching, setIsSearching] = useState(false) const [results, setResults] = useState([]) const [resultIndex, setResultIndex] = useState(0) const result = results[resultIndex] useEffect(() => { if (!giphyApiKey || !term) { setResults([]) return } setIsSearching(true) fetch( `https://api.giphy.com/v1/gifs/search?api_key=${giphyApiKey}&q=${term}&limit=20&rating=pg` ) .then(response => response.json()) .then(data => { const originalGiphys: GiphyGif[] = data.data const denormalizedGiphys = denormalizeGiphys(term, originalGiphys) setResults(denormalizedGiphys) setResultIndex(0) }) .catch(error => { console.error('Error fetching gifs:', error) }) .finally(() => { setIsSearching(false) }) }, [giphyApiKey, term]) const nextResult = useCallback(() => { setResultIndex(oldResultIndex => (oldResultIndex < results.length - 1 ? oldResultIndex + 1 : 0)) }, [results.length]) const prevResult = useCallback(() => { setResultIndex(oldResultIndex => (oldResultIndex > 0 ? oldResultIndex - 1 : results.length - 1)) }, [results.length]) return { isSearching, result, resultIndex, nextResult, prevResult, } } function denormalizeGiphys( term: string, giphys: GiphyGif[] ): DenormalizedGiphyAttachmentResourceForCreate[] { return giphys.map(giphy => ({ type: 'giphy', id: giphy.id, title: term, original_giphy_title: giphy.title, title_link: giphy.url, thumb_url: giphy.images.fixed_width.url, giphy: { original: giphy.images.original, fixed_height: giphy.images.fixed_height, fixed_height_still: giphy.images.fixed_height_still, fixed_height_downsampled: giphy.images.fixed_height_downsampled, fixed_width: giphy.images.fixed_width, fixed_width_still: giphy.images.fixed_width_still, fixed_width_downsampled: giphy.images.fixed_width_downsampled, }, })) }