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

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

import { SpotlightContainerDecorator } from "@enact/spotlight/SpotlightContainerDecorator";
import Spottable from "@enact/spotlight/Spottable";
import { setContainerLastFocusedElement } from "@enact/spotlight/src/container";

import { sendLogCuration } from "../../../actions/logActions";
import { getSubCategory } from "../../../actions/mainActions";
import { pushPanel } from "../../../actions/panelActions";
import TItemCard from "../../../components/TItemCard/TItemCard";
import TScroller from "../../../components/TScroller/TScroller";
import usePrevious from "../../../hooks/usePrevious";
import useScrollReset from "../../../hooks/useScrollReset";
import useScrollTo from "../../../hooks/useScrollTo";
import {
  LOG_CONTEXT_NAME,
  LOG_MESSAGE_ID,
  LOG_TP_NO,
  panel_names,
} from "../../../utils/Config";
import { SpotlightIds } from "../../../utils/SpotlightIds";
import CategoryNav from "../../HomePanel/SubCategory/CategoryNav/CategoryNav";
import css from "../../HomePanel/SubCategory/SubCategory.module.less";

const SpottableComponent = Spottable("div");
const Container = SpotlightContainerDecorator({ enterTo: null }, "div");
const ContainerBasic = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);

const getExpsOrdByLgCatCd = (array, value) => {
  const expsOrd = array.findIndex(({ lgCatCd }) => value === lgCatCd) + 1;
  return expsOrd.toString();
};

export default memo(function SubCategory({
  spotlightId,
  catCd,
  cateNm,
  handleItemFocus,
  handleShelfFocus,
  shelfLocation,
  shelfTitle,
}) {
  const dispatch = useDispatch();
  const { getScrollTo, scrollLeft } = useScrollTo();
  const { handleScrollReset, handleStopScrolling } = useScrollReset(
    scrollLeft,
    false
  );

  const categoryInfos = useSelector(
    (state) => state.home.menuData?.data?.homeCategory
  );
  const categoryItemInfos = useSelector(
    (state) => state.main.subCategoryData?.categoryItemInfos
  );

  const nowMenu = useSelector((state) => state.common.menu.nowMenu);

  const [currentLgCatCd, setCurrentLgCatCd] = useState(catCd ? catCd : null);
  const [currentLgCatNm, setCurrentLgCatNm] = useState(cateNm ? cateNm : null);
  const [drawChk, setDrawChk] = useState(false);
  const [firstChk, SetFirstChk] = useState(false);

  const nowMenuRef = usePrevious(nowMenu);

  useEffect(() => {
    if (categoryInfos && !currentLgCatCd && !currentLgCatNm) {
      const initialLgCatCd = categoryInfos[0].lgCatCd;
      const initialLgCatNm = categoryInfos[0].lgCatNm;
      setCurrentLgCatCd(initialLgCatCd);
      setCurrentLgCatNm(initialLgCatNm);
    }
  }, [categoryInfos]);

  useEffect(() => {
    if (catCd !== null) {
      setCurrentLgCatCd(catCd);
    }
    if (cateNm !== null) {
      setCurrentLgCatNm(cateNm);
    }
  }, [catCd, cateNm]);

  useEffect(() => {
    if (currentLgCatCd) {
      if (firstChk) {
        dispatch(
          getSubCategory(
            {
              lgCatCd: currentLgCatCd,
              pageSize: "10",
              tabType: "CAT00102",
              filterType: "CAT00202",
            },
            1
          )
        );
      }
      setDrawChk(true);
    }
  }, [currentLgCatCd, dispatch]);

  useEffect(() => {
    if (!nowMenuRef.current || !nowMenuRef.current.startsWith("Home")) {
      return;
    }

    if (categoryInfos) {
      const params = {
        expsOrd: getExpsOrdByLgCatCd(categoryInfos, currentLgCatCd),
        lgCatCd: currentLgCatCd,
        lgCatNm: currentLgCatNm,
        logTpNo: LOG_TP_NO.CURATION.HOME,
      };

      dispatch(sendLogCuration(params));
    }
  }, [categoryInfos, currentLgCatCd, currentLgCatNm]);

  const handleCategoryNav = useCallback(
    (lgCatCd, lgCatNm) => {
      if (currentLgCatCd === lgCatCd) {
        return;
      }
      setCurrentLgCatCd(lgCatCd);
      setCurrentLgCatNm(lgCatNm);

      SetFirstChk(true);
      handleScrollReset();

      setContainerLastFocusedElement(null, [SpotlightIds.HOME_CATEGORY_NAV]);
    },
    [currentLgCatCd]
  );

  const handleFocus = useCallback(
    (itemIndex) => () => {
      _handleItemFocus();

      if (itemIndex === 0) {
        handleScrollReset();
      }
    },
    [_handleItemFocus]
  );

  const handleBlur = useCallback(
    (itemIndex) => () => {
      if (itemIndex === 0) {
        handleStopScrolling();
      }
    },
    []
  );

  const handleCardClick = useCallback(
    (patnrId, prdtId) => () => {
      dispatch(
        pushPanel({
          name: panel_names.DETAIL_PANEL,
          panelInfo: { patnrId, prdtId, nowShelf: spotlightId },
        })
      );
    },
    []
  );

  const handleScrollRight = useCallback((e) => {
    const container = e.currentTarget?.parentNode;
    const x = container.scrollWidth - container.clientWidth;

    setTimeout(() => scrollLeft({ x, animate: true }));
  }, []);

  const handleMoreCardClick = useCallback((e) => {
    const lgCatCd = e.currentTarget?.getAttribute("data-catcd-num");
    const lgCatNm = e.currentTarget?.getAttribute("data-catcd-nm");
    const tab = 0;

    if (lgCatCd && lgCatNm) {
      dispatch(
        pushPanel({
          name: panel_names.CATEGORY_PANEL,
          panelInfo: {
            lgCatCd,
            lgCatNm,
            tab,
          },
        })
      );
    }
  }, []);

  const _handleItemFocus = useCallback(() => {
    if (handleItemFocus) {
      handleItemFocus();
    }
  }, [handleItemFocus]);

  const _handleShelfFocus = useCallback(() => {
    if (handleShelfFocus) {
      handleShelfFocus();
    }
  }, [handleShelfFocus]);

  return (
    <Container
      spotlightId={spotlightId}
      data-wheel-point
      onFocus={_handleShelfFocus}
    >
      <CategoryNav
        categoryInfos={categoryInfos}
        currentCategoryCode={currentLgCatCd}
        onCategoryNavClick={handleCategoryNav}
        type="home"
        data-title-index="subCategoryNav"
        handleItemFocus={_handleItemFocus}
        spotlightId="home_subCategoryNav"
      />

      <ContainerBasic spotlightId={SpotlightIds.HOME_CATEGORY_NAV}>
        <TScroller
          className={css.home}
          direction="horizontal"
          cbScrollTo={getScrollTo}
          noScrollByWheel
        >
          {categoryItemInfos &&
            categoryItemInfos?.subCatItemList.map(
              (
                {
                  prdtId,
                  imgUrl,
                  priceInfo,
                  prdtNm,
                  patnrId,
                  offerInfo,
                  brndNm,
                  patncNm,
                },
                itemIndex
              ) => {
                return (
                  <TItemCard
                    key={"subItem" + itemIndex}
                    contextName={LOG_CONTEXT_NAME.HOME}
                    messageId={LOG_MESSAGE_ID.SHELF_CLICK}
                    catNm={categoryItemInfos.catNm}
                    order={itemIndex + 1}
                    shelfId={spotlightId}
                    shelfLocation={shelfLocation}
                    shelfTitle={shelfTitle}
                    brandName={brndNm}
                    patnerName={patncNm}
                    imageAlt={prdtId}
                    imageSource={imgUrl}
                    priceInfo={priceInfo}
                    productName={prdtNm}
                    productId={prdtId}
                    onFocus={handleFocus(itemIndex)}
                    onBlur={handleBlur(itemIndex)}
                    onClick={handleCardClick(patnrId, prdtId)}
                    offerInfo={offerInfo}
                    data-catcd-num={currentLgCatCd}
                    data-catcd-nm={currentLgCatNm}
                    label={
                      itemIndex * 1 +
                      1 +
                      " of " +
                      categoryItemInfos?.subCatItemList.length
                    }
                    lastLabel=" go to detail, button"
                  />
                );
              }
            )}

          {drawChk && (
            <div className={css.addItem} onFocus={handleScrollRight}>
              <SpottableComponent
                className={css.displayBox}
                onClick={handleMoreCardClick}
                spotlightId={"home-cate-more-btn-" + currentLgCatCd}
                onFocus={_handleItemFocus}
                data-catcd-num={currentLgCatCd}
                data-catcd-nm={currentLgCatNm}
                aria-label="See more button"
              ></SpottableComponent>
            </div>
          )}
        </TScroller>
      </ContainerBasic>
    </Container>
  );
});
