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

import { ReactComponent as IconSearchGray } from "@assets/img/svg/ico_search_gray.svg";
import { ReactComponent as IconClose } from "@assets/img/svg/ico_close.svg";
import useSearch from "@src/hooks/useSearch";
import { useHistory } from "react-router";
import URLInfo from "@src/constants/URLInfo";
import { useOnClickOutside } from "usehooks-ts";
import AutoCompleteSearch from "../common/AutoCompleteSearch";

const cx = classNames.bind(styles);

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

const Search: React.FC<IOwnProps> = ({ onClose }) => {
  const history = useHistory();
  const searchRef = useRef(null);
  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 fakeComplete = [
    "test1",
    "test2",
    "test3",
    "test4",
    "test5",
    "test6",
    "test7",
    "test8",
    "test9",
    "test10",
  ];

  useOnClickOutside(searchRef, () => {
    setShowAutoComplete(false);
  });

  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={fakeComplete}
          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;
