import URLInfo from '@src/constants/URLInfo';
import { useEffect, useState } from 'react';
import { useHistory } from 'react-router';

interface IOwnProps {
  onSearch?: () => void;
}

const useSearch = (props?: IOwnProps) => {
  const history = useHistory();
  const [keyword, setKeyword] = useState<string>('');

  const handleSearch = () => {
    props?.onSearch?.();
  };

  const onKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key.toUpperCase() === 'ENTER') {
      handleSearch();
    }
  };

  const handleDeleteKeyword = () => {
    setKeyword('');
  };

  useEffect(() => {
    const keywordText = new URLSearchParams(window.location.href).get(
      URLInfo.SEARCH_PARAM.SEARCH_TEXT
    );

    if (keywordText) {
      const keyword = decodeURIComponent(keywordText);

      setKeyword(keyword);
    }
  }, [history.location.search]);

  return {
    keyword,
    setKeyword,
    onKeyPress,
    handleSearch,
    handleDeleteKeyword,
  };
};

export default useSearch;
