import { ReactComponent as IconActivity } from "@assets/img/svg/ico_activity.svg";
import { ReactComponent as IconArrow } from "@assets/img/svg/ico_arr_gray.svg";
import { ReactComponent as IconFacebook } from "@assets/img/svg/ico_facebook.svg";
import { ReactComponent as IconInstagram } from "@assets/img/svg/ico_insta.svg";
import { ReactComponent as IconSearchGray } from "@assets/img/svg/ico_search_gray.svg";
import { ReactComponent as IconTwitter } from "@assets/img/svg/ico_twitter.svg";
import { ReactComponent as IconLogo } from "@assets/img/svg/logo_metarare.svg";
import URLInfo from "@src/constants/URLInfo";
import LayerContainer from "@src/containers/common/LayerContainer";
import useLogin from "@src/hooks/useLogin";
import useSearch from "@src/hooks/useSearch";
import { fetchExploreHint } from "@src/store/reducers/ExploreReducer";
import { fetchUserInfo } from "@src/store/reducers/UserReducer";
import classNames from "classnames/bind";
import React, { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useHistory, useLocation } from "react-router";
import { Link } from "react-router-dom";
import { useDebounce, useOnClickOutside } from "usehooks-ts";
import AutoCompleteSearch from "../common/AutoCompleteSearch";
import ProfileModal from "../common/ProfileModal";
import { YoutubeIcon } from "../common/icon/youtube";
import styles from "./Header.scss";

const cx = classNames.bind(styles);

const Header: React.FC = () => {
  const searchRef = useRef(null);
  const history = useHistory();
  const dispatch = useDispatch();
  const [showAutoComplete, setShowAutoComplete] = useState<boolean>(false);
  const { userInfo, isUserInfoLoaded } = useSelector((store) => store.user);
  const onSearch = () => {
    history.push(URLInfo.getSearchResultUrl(keyword));
    setShowAutoComplete(false);
  };
  const SelectTextComplete = (text: string) => {
    history.push(URLInfo.getSearchResultUrl(text));
  };
  const { keyword, setKeyword, onKeyPress, handleSearch } = useSearch({
    onSearch,
  });
  const debouncedValue = useDebounce<string>(keyword, 1000);
  const [showCommunity, setShowCommunity] = useState(false);
  const [showProfile, setShowProfile] = useState<boolean>(false);
  const location = useLocation();
  const { handleClickLoginButton, loginText } = useLogin();
  const searchText = new URLSearchParams(location.search).get(
    URLInfo.SEARCH_PARAM.SEARCH_TEXT
  );
  const { hint } = useSelector((state) => state.explore);
  useEffect(() => {
    if (showProfile) {
      dispatch(fetchUserInfo());
    }
  }, [showProfile]);

  const onClickLogin = () => {
    if (isUserInfoLoaded || userInfo) {
      handleClickLoginButton();
    }
  };

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

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

  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("header_wrap")}>
      <div className={cx("header_group")}>
        <h1 className={cx("logo")}>
          <Link to={URLInfo.HOME} className={cx("link_logo")}>
            <IconLogo className={cx("ico_logo")} />
            <span className={cx("name")}>MetaRare</span>
          </Link>
        </h1>
        <div className={cx("gnb")}>
          <div className={cx("search_area")} ref={searchRef}>
            <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>
          <ul className={cx("menu_list")}>
            {/* <li className={cx("menu_item")}>
              <Link to={URLInfo.EXPLORE} className={cx("menu")}>
                탐색하기
              </Link>
            </li>
            {userInfo && (
              <li className={cx("menu_item")}>
                <Link
                  to={URLInfo.getProfileUserUrl(userInfo.simple_profile.name)}
                  className={cx("menu")}
                >
                  내 프로필
                </Link>
              </li>
            )} */}
            {/* <li className={cx("menu_item")}>
              <Link to={URLInfo.ACTIVITY} className={cx("menu")}>
                활동
              </Link>
            </li> */}

            {/* <li className={cx("menu_item")}>
              <a
                href="https://reactnavigation.org/"
                target={"_blank"}
                className={cx("menu")}
              >
                test
              </a>
            </li> */}
            <li className={cx("menu_item")}>
              <button
                type="button"
                className={cx("btn_community")}
                onClick={() => setShowCommunity(!showCommunity)}
              >
                커뮤니티
                <IconArrow className={cx("ico_arr")} />
              </button>
              {showCommunity && (
                <div className={cx("ly_community")}>
                  <div
                    className={cx("dimmed")}
                    onClick={() => setShowCommunity(false)}
                  />
                  <ul className={cx("community_list")}>
                    {/* <li className={cx('community_item')}>
                      <Link to={"#"} className={cx('link_community')} onClick={() => {window.open(URLInfo.registerArtistUrl, '_blank')}}>작가등록</Link>                      
                    </li> */}
                    <li className={cx("community_item")}>
                      <a
                        href="https://drive.google.com/drive/folders/1rHqNh2zosyYv9XfUmbOAwWvSQMSynoF0?usp=sharing"
                        className={cx("link_community")}
                        target="_blank"
                      >
                        백서 (White paper)
                      </a>
                    </li>
                    <li className={cx("community_item")}>
                      <Link to="#" className={cx("link_community_number")}>
                        02-2038-8262
                      </Link>
                      <p className={cx("link_community_number")}>
                        (월~금 9am~6pm 유료전화)
                      </p>
                    </li>
                    <li className={cx("community_item")}>
                      <Link to="#" className={cx("link_community")}>
                        구독하기 (Subscribe)
                      </Link>
                    </li>
                    <li className={cx("community_item")}>
                      <Link to={URLInfo.GUIDE} className={cx("link_community")}>
                        사용방법
                      </Link>
                    </li>
                    <li className={cx("community_sns")}>
                      <a
                        href="https://twitter.com/metarare_nft                        "
                        target="_blank"
                        className={cx("link_sns")}
                      >
                        <span className={cx("blind")}>Twitter</span>
                        <IconTwitter className={cx("ico_sns")} />
                      </a>
                      <a
                        href="https://www.instagram.com/metarare_official/"
                        target="_blank"
                        className={cx("link_sns")}
                      >
                        <span className={cx("blind")}>Instagram</span>
                        <IconInstagram className={cx("ico_sns")} />
                      </a>
                      <a
                        href="https://www.youtube.com/channel/UC08Jk0jzWohvjQT0H62Y17Q
"
                        target="_blank"
                        className={cx("link_sns_u")}
                      >
                        <YoutubeIcon />
                        <span className={cx("blind")}>Youtube</span>
                      </a>
                      <a
                        href="https://www.facebook.com/MetaRare-NFT-lnc-112216471398493"
                        target="_blank"
                        className={cx("link_sns")}
                      >
                        <span className={cx("blind")}>Facebook</span>
                        <IconFacebook className={cx("ico_sns_facebook")} />
                      </a>
                    </li>
                  </ul>
                </div>
              )}
            </li>
            <li className={cx("menu_item")}>
              <Link to={URLInfo.EXPLORE} className={cx("menu")}>
                Top 100
              </Link>
            </li>
          </ul>
          <div className={cx("btn_area")}>
            <Link to={URLInfo.ACTIVITY} className={cx("link_activity")}>
              <span className={cx("blind")}>Activity</span>
              <IconActivity className={cx("ico", "ico_activity")} />
            </Link>
            <Link to={URLInfo.CREATE} className={cx("link", "link_make")}>
              만들기
            </Link>
            <button
              type="button"
              className={cx("link", "link_login")}
              onClick={onClickLogin}
            >
              {(isUserInfoLoaded || userInfo) && <>{loginText}</>}
            </button>
            {userInfo && (
              <button
                type="button"
                className={cx("btn_profile")}
                onClick={() => setShowProfile(true)}
              >
                <span className={cx("blind")}>Profile</span>
                <img
                  src={
                    userInfo?.simple_profile.thumbnail_image ||
                    "/static/img/svg/user_profile.svg"
                  }
                  alt=""
                  width="40"
                  height="40"
                  className={cx("img_profile")}
                />
              </button>
            )}
          </div>
        </div>
      </div>
      <LayerContainer
        onClose={() => setShowProfile(false)}
        style={{ display: userInfo && showProfile ? "block" : "none" }}
      >
        <ProfileModal onClose={() => setShowProfile(false)} />
      </LayerContainer>
    </div>
  );
};

export default Header;
