import React, { useEffect } from "react";
import classNames from "classnames/bind";

import styles from "./Explore.scss";
import ExploreContentContainer from "@src/containers/common/ExploreContentContainer";
import { useDispatch, useSelector } from "react-redux";
import {
  fetchExploreHome,
  fetchExploreSearch,
  resetExploreHome,
} from "@src/store/reducers/ExploreReducer";
import useExploreFilter from "@src/hooks/useExploreFilter";
import { useCallbackAwaitStateSync } from "use-callback-await-state-sync";
import useMore from "@src/hooks/useMore";
import URLInfo from "@src/constants/URLInfo";
import { IFilter } from "metarare";
import { useIsFirstRender } from "usehooks-ts";

const cx = classNames.bind(styles);

interface IOwnProps {}

const Explore: React.FC<IOwnProps> = ({}) => {
  const isFirstRender = useIsFirstRender();
  const dispatch = useDispatch();
  const { list, isExploreListLoaded } = useSelector((store) => store.explore);
  const searchText = new URLSearchParams(location.search).get(
    URLInfo.SEARCH_PARAM.SEARCH_TEXT
  );

  const filterProps = useExploreFilter({ list });
  const dispatchExploreHome = (offset: number, limit: number) => {
    const commonBody: IFilter = {
      offset,
      limit,
      collection_name: filterProps.collection,
      currency:
        filterProps.maxPrice && filterProps.minPrice
          ? filterProps.selectedCurrency
          : "",
      currency_amount_end: filterProps.maxPrice,
      currency_amount_start: filterProps.minPrice,
      network: filterProps.networkType,
      sale_type: filterProps.saleType,
    };
    if (searchText) {
      dispatch(
        fetchExploreSearch({
          ...commonBody,
          token_name: searchText,
        })
      );
    } else {
      dispatch(fetchExploreHome(commonBody));
    }
  };

  const { onClickMore, showMore, resetPagination, defaultDisplayCnt } = useMore(
    {
      list,
      dispatchFnc: dispatchExploreHome,
      setSelectedFilterType: filterProps.setSelectedFilterType,
    }
  );

  const fetchInit = () => {
    dispatch(resetExploreHome());
    resetPagination();
    dispatchExploreHome(0, defaultDisplayCnt);
  };

  const filterHandler = useCallbackAwaitStateSync(() => {
    fetchInit();
  });

  useEffect(() => {
    if (isFirstRender) return;
    fetchInit();
  }, [searchText]);

  return (
    <div className={cx("explore")}>
      <div className={cx("explore_title")}>탐색하기 🔍</div>
      <ExploreContentContainer
        list={filterProps.exploreList}
        filterProps={filterProps}
        handler={filterHandler}
        onClickMore={onClickMore}
        showMore={showMore}
        isLoaded={isExploreListLoaded}
      />
    </div>
  );
};

export default Explore;
