import classNames from "classnames/bind";
import React, { useEffect, useRef, useState } from "react";
import styles from "./Search.scss";

import { ReactComponent as IconClose } from "@assets/img/svg/ico_close.svg";
import { ReactComponent as IconSearchGray } from "@assets/img/svg/ico_search_gray.svg";
import URLInfo from "@src/constants/URLInfo";
import useSearch from "@src/hooks/useSearch";
import { useDispatch, useSelector } from "react-redux";
import { useHistory, useLocation } from "react-router";
import { useDebounce, useOnClickOutside } from "usehooks-ts";
import AutoCompleteSearch from "../common/AutoCompleteSearch";
import { fetchExploreHint } from "@src/store/reducers/ExploreReducer";

const cx = classNames.bind(styles);

interface IOwnProps {
  onClose: () => void;
}

const Search: React.FC<IOwnProps> = ({ onClose }) => {
  const history = useHistory();
  const searchRef = useRef(null);
  const dispatch = useDispatch();
  const { hint } = useSelector((state) => state.explore);
  const [showAutoComplete, setShowAutoComplete] = useState<boolean>(false);
  const onSearch = () => {
    history.push(URLInfo.getSearchResultUrl(keyword));
    onClose();
  };
  const SelectTextComplete = (text: string) => {
    history.push(URLInfo.getSearchResultUrl(text));
    onClose();
  };

  const { keyword, setKeyword, onKeyPress, handleSearch } = useSearch({
    onSearch,
  });
  const debouncedValue = useDebounce<string>(keyword, 1000);
  const location = useLocation();
  const searchText = new URLSearchParams(location.search).get(
    URLInfo.SEARCH_PARAM.SEARCH_TEXT
  );
  useOnClickOutside(searchRef, () => {
    setShowAutoComplete(false);
  });

  const dispatchHint = (token_name: string) => {
    dispatch(
      fetchExploreHint({
        token_name,
      })
    );
  };

  useEffect(() => {
    dispatchHint(keyword);
    if (URLInfo.isExplorePage(location)) {
      history.push(URLInfo.getSearchResultUrl(keyword));
    }
  }, [debouncedValue]);

  useEffect(() => {
    if (!URLInfo.isExplorePage(location)) {
      setKeyword("");
    } else {
      if (searchText) {
        setKeyword(searchText);
      }
    }
  }, [location]);

  return (
    <div className={cx("ly_search")} ref={searchRef}>
      <div className={cx("input_box")}>
        <input
          type="text"
          placeholder="작가(NFT)이름을 입력해주세요"
          className={cx("input_search")}
          value={keyword}
          onKeyPress={onKeyPress}
          onChange={(e) => setKeyword(e.target.value)}
          onFocus={() => {
            setShowAutoComplete(true);
          }}
        />
        <button className={cx("btn_search")} onClick={handleSearch}>
          <span className={cx("blind")}>Search</span>
          <IconSearchGray className={cx("ico_search")} />
        </button>
        <AutoCompleteSearch
          show={showAutoComplete}
          data={hint}
          onClick={(e) => {
            setShowAutoComplete(false);
            SelectTextComplete(e);
            setKeyword(e);
          }}
        />
      </div>
      <button className={cx("btn_close")} onClick={onClose}>
        <span className={cx("blind")}>Close</span>
        <IconClose className={cx("ico_close")} />
      </button>
    </div>
  );
};

export default Search;
