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 "./FeaturedCreators.module.less";
import FeaturedCreatorsContents from "./FeaturedCreatorsContents/FeaturedCreatorsContents";
import FeaturedCreatorsNav from "./FeaturedCreatorsNav/FeaturedCreatorsNav";

const STRING_CONF = {
  FEATURED_CREATORS: "FEATURED CREATORS",
};
const Container = SpotlightContainerDecorator(
  { leaveFor: { right: "" }, enterTo: null },
  "div"
);

const FeaturedCreators = ({
  brandCreatorsInfo,
  barndCreatorsShowInfo,
  fromGNB,
  fromQuickMenu,
  handleItemFocus,
  order,
  shelfOrder,
  selectedHstNm,
  selectedPatncNm,
  selectedPatnrId,
  setSelectedHstNm,
  spotlightId,
}) => {
  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 = "featured-creators, 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(
            "featured-creators, Heading1,",
            ""
          );
          c.setAttribute("aria-label", newcAriaLabel);
        }
      }
    } else {
      return;
    }
  }, [handleItemFocus, firstChk]);

  return (
    <Container
      className={css.container}
      data-wheel-point
      data-shelf-order={order}
      spotlightId={spotlightId}
    >
      <SectionTitle
        title={$L(STRING_CONF.FEATURED_CREATORS)}
        data-title="featured-creators"
      />
      <FeaturedCreatorsNav
        brandCreatorsInfo={brandCreatorsInfo}
        fromGNB={fromGNB}
        fromQuickMenu={fromQuickMenu}
        handleItemFocus={_handleItemFocus}
        selectedHstNm={selectedHstNm}
        selectedPatncNm={selectedPatncNm}
        selectedPatnrId={selectedPatnrId}
        setSelectedHstNm={setSelectedHstNm}
      />
      {barndCreatorsShowInfo.map((barndCreatorsShowInfoItem, contentsIndex) => (
        <FeaturedCreatorsContents
          barndCreatorsShowInfoItem={barndCreatorsShowInfoItem}
          contentsIndex={contentsIndex}
          handleItemFocus={_handleItemFocus}
          key={`${spotlightId}-${contentsIndex}`}
          selectedHstNm={selectedHstNm}
          selectedPatnrId={selectedPatnrId}
          spotlightId={spotlightId}
        />
      ))}
    </Container>
  );
};

export default memo(FeaturedCreators);
