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

import { useSelector } from "react-redux";

import Spotlight from "@enact/spotlight";
import { SpotlightContainerDecorator } from "@enact/spotlight/SpotlightContainerDecorator";

import SectionTitle from "../../../components/SectionTitle/SectionTitle";
import TScroller from "../../../components/TScroller/TScroller";
import useScrollReset from "../../../hooks/useScrollReset";
import useScrollTo from "../../../hooks/useScrollTo";
import { $L, scaleW } from "../../../utils/helperMethods";
import css from "./HomeOnSale.module.less";
import HomeOnSaleItem from "./HomeOnSaleItem/HomeOnSaleItem";
import { LOG_CONTEXT_NAME, LOG_MESSAGE_ID } from "../../../utils/Config";

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

const HomeOnSale = ({
  order,
  scrollTopBody,
  handleItemFocus,
  handleShelfFocus,
  spotlightId,
  shelfLocation,
  shelfTitle,
  ...rest
}) => {
  const [firstChk, setFirstChk] = useState(0);

  const { getScrollTo, scrollLeft } = useScrollTo();
  const { handleScrollReset, handleStopScrolling } = useScrollReset(
    scrollLeft,
    true
  );

  const homeOnSaleInfos = useSelector(
    (state) => state.onSale.homeOnSaleData?.data.homeOnSaleInfos
  );
  const { cursorVisible } = useSelector((state) => state.common.appStatus);

  const orderStyle = useMemo(() => ({ order: order }), [order]);

  const handleScrollRight = (e) => {
    const container = e.currentTarget?.parentNode;

    const x = container.scrollWidth - container.clientWidth;

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

  const handleFocus = useCallback(
    (index) => (e) => {
      _handleItemFocus();

      if (index === 0) {
        handleScrollReset();
      }

      if (firstChk === 0 && index === 0) {
        const c = Spotlight.getCurrent();
        if (c) {
          let cAriaLabel = c.getAttribute("aria-label");
          cAriaLabel = "On Sale, Heading 1," + cAriaLabel;
          c.setAttribute("aria-label", cAriaLabel);
        }
        setFirstChk(1);
      } else if (firstChk === 1 && index === 0) {
        const c = Spotlight.getCurrent();
        if (c) {
          let cAriaLabel = c.getAttribute("aria-label");
          if (cAriaLabel) {
            const newcAriaLabel = cAriaLabel.replace("On Sale, Heading 1,", "");
            c.setAttribute("aria-label", newcAriaLabel);
          }
        }
      } else {
        return;
      }

      if (index === homeOnSaleInfos?.length - 1) {
        handleScrollRight(e);
      }

      if (cursorVisible) {
        return;
      }
    },
    [
      cursorVisible,
      _handleItemFocus,
      handleScrollReset,
      handleScrollRight,
      homeOnSaleInfos?.length,
      scrollTopBody,
      firstChk,
    ]
  );

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

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

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

  // console.log("#homeOnSaleInfos", homeOnSaleInfos);
  return (
    <Container
      {...rest}
      className={css.container}
      style={orderStyle}
      spotlightId={spotlightId}
      data-wheel-point={true}
      onFocus={_handleShelfFocus}
    >
      <div className={css.onSaleWrap}>
        <SectionTitle
          className={css.subTitle}
          title={$L("ON SALE")}
          data-title-index="homeOnSale"
          label="ON SALE"
        />
        <div className={css.onSaleItem}>
          <TScroller
            cbScrollTo={getScrollTo}
            direction="horizontal"
            noScrollByWheel
            className={css.grid}
          >
            <>
              {homeOnSaleInfos &&
                homeOnSaleInfos.map((itemData, index) => {
                  return (
                    <HomeOnSaleItem
                      {...rest}
                      key={index}
                      spotlightId={spotlightId}
                      homeOnSaleInfos={homeOnSaleInfos}
                      itemData={itemData}
                      onFocus={handleFocus(index)}
                      onBlur={handleBlur(index)}
                      label={index * 1 + 1 + " of " + homeOnSaleInfos.length}
                      lastLabel=" go to detail, button"
                      contextName={LOG_CONTEXT_NAME.HOME}
                      messageId={LOG_MESSAGE_ID.SHELF_CLICK}
                      shelfLocation={shelfLocation}
                      shelfId={spotlightId}
                      shelfTitle={shelfTitle}
                      productId={itemData.prdtId}
                      productName={itemData.prdtNm}
                      order={itemData.expsOrd}
                      catNm={itemData.catNm}
                      partner={itemData.patncNm}
                      brandName={itemData.brndNm}
                    />
                  );
                })}
              <div className={css.addItem}></div>
            </>
          </TScroller>
        </div>
      </div>
    </Container>
  );
};

export default HomeOnSale;
