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

import { useDispatch } from "react-redux";

import { getOnSaleInfo } from "../../api/onSaleApi";
import TPanel from "../../components/TPanel/TPanel";
import CategoryNav from "./CategoryNav/CategoryNav";
import css from "./OnSalePanel.module.less";
import OnSaleProductCard from "./OnSaleProductCard/OnSaleProductCard";
import OnSaleProductsGrid from "./OnSaleProductsGrid/OnSaleProductsGrid";

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

  const [currentLgCatCdIndex, setCurrentLgCatCdIndex] = useState(0);
  const [lgCatCd, setLgCatCd] = useState("");
  const [categoryInfos, setCategoryInfos] = useState([]);
  const [saleInfos, setSaleInfos] = useState([]);
  const [saleProductInfos, setSaleProductInfos] = useState([]);

  const handleCategoryNav = (lgCatCd, index) => {
    if (currentLgCatCdIndex === index) {
      return;
    }
    setCurrentLgCatCdIndex(index);
    setLgCatCd(lgCatCd);
  };

  const getOnSaleInfoData = async (lgCatCd) => {
    try {
      const onSaleInfoData = await getOnSaleInfo({
        lgCatCd,
        categoryIncFlag: "Y",
      });
      console.log("On Sale Data:", onSaleInfoData);

      if (onSaleInfoData) {
        if (lgCatCd === "") {
          setCategoryInfos(onSaleInfoData.categoryInfos);
        }

        setSaleInfos(onSaleInfoData.saleInfos);

        let saleProducts = [];

        for (let index = 0; index < onSaleInfoData.saleInfos.length; index++) {
          saleProducts.push(onSaleInfoData.saleInfos[index].saleProductInfos);
        }

        setSaleProductInfos(saleProducts);
      }
    } catch (error) {
      console.error("Error fetching on sale:", error);
    }
  };

  useEffect(() => {
    getOnSaleInfoData(lgCatCd);
  }, [lgCatCd, currentLgCatCdIndex]);

  return (
    <TPanel className={css.container}>
      <CategoryNav
        categoryInfos={categoryInfos}
        currentLgCatCdIndex={currentLgCatCdIndex}
        onCategoryNavClick={handleCategoryNav}
      />

      <section className={css.onSaleProducts}>
        {saleInfos.map(({ saleNm }, index) => {
          return (
            <OnSaleProductsGrid key={saleNm} saleNm={saleNm}>
              {saleProductInfos[index].map((saleProduct) => {
                return (
                  <OnSaleProductCard
                    key={saleProduct.prdtId}
                    saleProduct={saleProduct}
                  />
                );
              })}
            </OnSaleProductsGrid>
          );
        })}
      </section>
    </TPanel>
  );
}
