import { Feature, Icon } from '@preply/ds-core-types';
import React, { FC, ReactNode, createContext, useCallback, useEffect, useState } from 'react';
import iconsData from '@preply/ds-media-icons/data/icons.json';

import { IconsContext } from './IconsContext';

export interface IconSearchContextShape {
    terms: string;
    results: Feature[];
    setSearchTerms: (terms: string) => void;
}

export const IconSearchContext = createContext<IconSearchContextShape>({
    terms: '',
    results: [],
    setSearchTerms: () => null,
});

const icons = new IconsContext(iconsData as Icon[]);

export const IconSearchProvider: FC<{ children?: ReactNode }> = ({ children }) => {
    const [terms, setTerms] = useState<string>('');
    const [results, setResults] = useState<Feature[]>([]);

    const setSearchTerms = useCallback((t: string) => setTerms(t), [setTerms]);

    useEffect(() => {
        const res = icons.searchIcons({ terms });
        setResults(res);
    }, [terms]);

    return (
        <IconSearchContext.Provider value={{ terms, results, setSearchTerms }}>
            {children}
        </IconSearchContext.Provider>
    );
};
