import {
  createContext,
  type FC,
  useCallback,
  useContext,
  useMemo,
  useState,
} from 'react';

export type SearchHighlightContextValue = {
  isSearchOpen: boolean;
  searchQuery: string;
  matchedMessageIds: string[];
  openSearch: () => void;
  closeSearch: () => void;
  setSearchQuery: (query: string) => void;
  setMatchedMessageIds: (messageIds: string[]) => void;
};

export const SearchHighlightContext =
  createContext<SearchHighlightContextValue>({
    isSearchOpen: false,
    searchQuery: '',
    matchedMessageIds: [],
    openSearch: () => null,
    closeSearch: () => null,
    setSearchQuery: () => null,
    setMatchedMessageIds: () => null,
  });

export const SearchHighlightProvider: FC<React.PropsWithChildren> = ({
  children,
}) => {
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [matchedMessageIds, setMatchedMessageIds] = useState<string[]>([]);

  const openSearch = useCallback(() => {
    setIsSearchOpen(true);
  }, []);

  const closeSearch = useCallback(() => {
    setIsSearchOpen(false);
    setSearchQuery('');
    setMatchedMessageIds([]);
  }, []);

  const value = useMemo(
    () => ({
      isSearchOpen,
      searchQuery,
      matchedMessageIds,
      openSearch,
      closeSearch,
      setSearchQuery,
      setMatchedMessageIds,
    }),
    [isSearchOpen, searchQuery, matchedMessageIds, openSearch, closeSearch],
  );

  return (
    <SearchHighlightContext.Provider value={value}>
      {children}
    </SearchHighlightContext.Provider>
  );
};

export const useSearchHighlight = () => useContext(SearchHighlightContext);

export default SearchHighlightContext;
