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

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

import SectionTitle from "../../../components/SectionTitle/SectionTitle";
import { $L } from "../../../utils/helperMethods";
import css from "./FeaturedBestSeller.module.less";
import FeaturedBestSellerList from "./FeaturedBestSellerList/FeaturedBestSellerList";

const STRING_CONF = {
  BEST_SELLER: "BEST SELLER",
};

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

const FeaturedBestSeller = ({
  brandBestSellerInfo,
  handleItemFocus,
  order,
  shelfOrder,
  spotlightId,
  selectedPatnrId,
  shelfTitle,
}) => {
  const [firstChk, setFirstChk] = useState(0);

  const _handleItemFocus = useCallback(() => {
    if (handleItemFocus) handleItemFocus(spotlightId, shelfOrder);

    const c = Spotlight.getCurrent();
    if (firstChk === 0) {
      if (c) {
        let cAriaLabel = c.getAttribute("aria-label");
        if (cAriaLabel) {
          cAriaLabel = "best-seller, Heading1," + cAriaLabel;
          c.setAttribute("aria-label", cAriaLabel);
        }
      }
      setFirstChk(1);
    } else if (firstChk === 1) {
      if (c) {
        let cAriaLabel = c.getAttribute("aria-label");
        if (cAriaLabel) {
          const newcAriaLabel = cAriaLabel.replace(
            "best-seller, Heading1,",
            ""
          );
          c.setAttribute("aria-label", newcAriaLabel);
        }
      }
    } else {
      return;
    }
  }, [handleItemFocus, firstChk]);

  return (
    <Container
      className={css.container}
      data-shelf-order={order}
      data-wheel-point
      spotlightId={spotlightId}
    >
      <SectionTitle
        title={$L(STRING_CONF.BEST_SELLER)}
        data-title="best-seller"
        label="best-seller Heading 1"
      />
      <FeaturedBestSellerList
        brandBestSellerInfo={brandBestSellerInfo}
        handleItemFocus={_handleItemFocus}
        selectedPatnrId={selectedPatnrId}
        spotlightId={spotlightId}
        shelfOrder={shelfOrder}
        shelfTitle={shelfTitle}
      />
    </Container>
  );
};

export default memo(FeaturedBestSeller);
