import React, { useEffect, useState } from "react";

import { useDispatch, useSelector } from "react-redux";

import { getOnSaleInfo } from "../../actions/onSaleActions";
import TBody from "../../components/TBody/TBody";
import TopButton from "../../components/TopButton/TopButton";
import TPanel from "../../components/TPanel/TPanel";
import { SpotlightIds } from "../../utils/SpotlightIds";
import CategoryNav from "../OnSalePanel/CategoryNav/CategoryNav";
import css from "./OnSalePanel.module.less";
import OnSaleProductList from "./OnSaleProductList/OnSaleProductList";

export default function OnSalePanel() {
  const dispatch = useDispatch();

  const categoryInfos = useSelector(
    (state) => state.onSale.onSaleData.categoryInfos
  );
  const saleInfos = useSelector((state) => state.onSale.onSaleData.saleInfos);

  const [currentCategoryCode, setCurrentCategoryCode] = useState();
  const [targetId, setTargetId] = useState();

  useEffect(() => {
    if (categoryInfos && !currentCategoryCode) {
      const initialLgCatCd = categoryInfos[0].lgCatCd;
      setCurrentCategoryCode(initialLgCatCd);
    }
  }, []);

  useEffect(() => {
    if (currentCategoryCode) {
      dispatch(
        getOnSaleInfo({ categoryIncFlag: "Y", lgCatCd: currentCategoryCode })
      );
    }
  }, [currentCategoryCode, dispatch]);

  useEffect(() => {
    if (saleInfos) {
      const id = saleInfos[0].saleProductInfos[0].prdtId;
      setTargetId(id);
    }
  }, [dispatch, saleInfos]);

  return (
    <TPanel className={css.container}>
      <CategoryNav
        categoryInfos={categoryInfos}
        currentCategoryCode={currentCategoryCode}
        setCurrentCategoryCode={setCurrentCategoryCode}
      />
      <TBody className={css.tBody}>
        {saleInfos &&
          saleInfos.map(({ saleNm, saleProductInfos }) => (
            <OnSaleProductList
              key={saleNm}
              saleName={saleNm}
              saleProductInfos={saleProductInfos}
            />
          ))}
        <TopButton targetId={SpotlightIds.TITEM_CARD + targetId} />
      </TBody>
    </TPanel>
  );
}
