import React, { useCallback, useEffect, useRef } from "react";

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

import { Job } from "@enact/core/util";
import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import {
  getContainerId,
  setContainerLastFocusedElement,
} from "@enact/spotlight/src/container";

import { pushPanel, updatePanel } from "../../../../actions/panelActions";
import TItemCard, {
  removeDotAndColon,
} from "../../../../components/TItemCard/TItemCard";
import TVirtualGridList from "../../../../components/TVirtualGridList/TVirtualGridList";
import useScrollTo from "../../../../hooks/useScrollTo";
import {
  LOG_CONTEXT_NAME,
  LOG_MESSAGE_ID,
  panel_names,
} from "../../../../utils/Config";
import { getTranslate3dValueByDirection } from "../../../../utils/helperMethods";
import css from "./FeaturedBestSellerList.module.less";

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

export default function FeaturedBestSellerList({
  brandBestSellerInfo,
  handleItemFocus,
  selectedPatnrId,
  spotlightId,
  shelfTitle,
  shelfLocation,
  shelfOrder,
}) {
  const { getScrollTo, scrollLeft } = useScrollTo();

  const dispatch = useDispatch();

  const panelInfo = useSelector((state) => state.panels.panels[0]?.panelInfo);

  const cursorVisible = useSelector(
    (state) => state.common.appStatus.cursorVisible
  );

  const scrollLeftJob = useRef(new Job((func) => func(), 0));

  useEffect(() => {
    if (panelInfo?.section !== "best-seller" || !panelInfo?.x) {
      return;
    }

    const scrollLeftJobValue = scrollLeftJob.current;
    const { x } = panelInfo;

    scrollLeftJobValue.start(() => scrollLeft({ x }));

    return () => scrollLeftJobValue.stop();
  }, [panelInfo, scrollLeft]);

  useEffect(() => {
    const containerId = "featured-best-seller-list-id";
    const container = document.getElementById(containerId);

    if (container) {
      const childrenId = getContainerId(container?.children[0].children[0]);

      if (childrenId) {
        setContainerLastFocusedElement(null, [containerId, childrenId]);
      }
    }

    scrollLeft();
  }, [scrollLeft, selectedPatnrId]);

  const handleClick = useCallback(
    (patnrId, prdtId) => (e) => {
      const tItemCard = e.currentTarget;

      const lastFocusedTarget = Spotlight.getCurrent();
      const lastFocusedTargetId =
        lastFocusedTarget?.getAttribute("data-spotlight-id");

      const xContainer = tItemCard?.parentNode?.parentNode;

      if (lastFocusedTargetId && xContainer) {
        const section = "best-seller";
        const x = getTranslate3dValueByDirection(xContainer);

        dispatch(
          updatePanel({
            name: panel_names.FEATURED_BRANDS_PANEL,
            panelInfo: {
              lastFocusedTargetId,
              patnrId,
              section,
              x,
            },
          })
        );
      }

      dispatch(
        pushPanel({
          name: panel_names.DETAIL_PANEL,
          panelInfo: { patnrId, prdtId },
        })
      );
    },
    [dispatch]
  );

  const handleFocus = useCallback(() => {
    if (handleItemFocus) {
      handleItemFocus();
    }

    if (cursorVisible) {
      return;
    }
  }, [cursorVisible, handleItemFocus]);
  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const {
        imgUrl,
        offerInfo,
        patnrId,
        prdtNm,
        prdtId,
        priceInfo,
        rankOrd,
        patncNm,
        brndNm,
        lgCatNm,
      } = brandBestSellerInfo[index];
      const rankText =
        rankOrd === 1
          ? rankOrd + "st,"
          : rankOrd === 2
          ? rankOrd + "nd,"
          : rankOrd === 3
          ? rankOrd + "rd,"
          : rankOrd + "th,";

      return (
        <TItemCard
          catNm={lgCatNm}
          contextName={LOG_CONTEXT_NAME.FEATURED_BRANDS}
          messageId={LOG_MESSAGE_ID.SHELF_CLICK}
          order={rankOrd}
          patnerName={patncNm}
          brandName={brndNm}
          shelfId={spotlightId}
          shelfLocation={shelfOrder}
          shelfTitle={shelfTitle}
          imageAlt={prdtNm}
          imageSource={imgUrl}
          isBestSeller
          rank={rankOrd}
          onClick={handleClick(patnrId, prdtId)}
          onFocus={handleFocus}
          offerInfo={offerInfo}
          priceInfo={priceInfo}
          productId={prdtId}
          productName={prdtNm}
          spotlightId={"best-seller-spotlightId-" + removeDotAndColon(prdtId)}
          firstLabel={rankText}
          label={index * 1 + 1 + " of " + brandBestSellerInfo.length}
          lastLabel=" go to detail, button"
          {...rest}
        />
      );
    },
    [brandBestSellerInfo, handleClick, handleFocus]
  );

  return (
    <Container
      className={css.container}
      id={"featured-best-seller-list-id"}
      spotlightId={"featured-best-seller-list-id"}
    >
      {brandBestSellerInfo && (
        <TVirtualGridList
          cbScrollTo={getScrollTo}
          className={css.tVirtualGridList}
          dataSize={brandBestSellerInfo.length}
          direction="horizontal"
          itemHeight={438}
          itemWidth={324}
          spacing={18}
          renderItem={renderItem}
        />
      )}
    </Container>
  );
}
