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 "./UpComing.module.less";
import UpComingList from "./UpComingList/UpComingList";

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

const STRING_CONF = {
  UPCOMING: "UPCOMING",
};

const UpComing = ({
  brandLiveChannelUpcoming,
  handleItemFocus,
  order,
  shelfOrder,
  shelfTitle,
  selectedPatnrId,
  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");
        cAriaLabel = "UPCOMING, 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("UPCOMING, 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.UPCOMING)}
        data-title="upcoming"
        aria-label="upcoming heading 1"
      />
      <UpComingList
        brandLiveChannelUpcoming={brandLiveChannelUpcoming}
        handleItemFocus={_handleItemFocus}
        selectedPatnrId={selectedPatnrId}
        shelfTitle={shelfTitle}
        shelfOrder={shelfOrder}
        shelfId={spotlightId}
      />
    </Container>
  );
};

export default memo(UpComing);
