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

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

import Spotlight from "@enact/spotlight";
import { SpotlightContainerDecorator } from "@enact/spotlight/SpotlightContainerDecorator";
import Spottable from "@enact/spotlight/Spottable";
import { getContainerId } from "@enact/spotlight/src/container";

import { updateHomeInfo } from "../../../actions/homeActions";
import { pushPanel } from "../../../actions/panelActions";
import { startVideoPlayer } from "../../../actions/playActions";
import SectionTitle from "../../../components/SectionTitle/SectionTitle";
import TItemCard, {
  IMAGETYPES,
  TYPES,
} from "../../../components/TItemCard/TItemCard";
import TScroller from "../../../components/TScroller/TScroller";
import useScrollReset from "../../../hooks/useScrollReset";
import useScrollTo from "../../../hooks/useScrollTo";
import {
  LOG_CONTEXT_NAME,
  LOG_MESSAGE_ID,
  panel_names,
} from "../../../utils/Config";
import { $L, scaleW } from "../../../utils/helperMethods";
import { SpotlightIds } from "../../../utils/SpotlightIds";
import { TEMPLATE_CODE_CONF } from "../HomePanel";
import css from "../PopularShow/PopularShow.module.less";

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

const PopularShow = ({
  homeChk = true,
  order,
  scrollTopBody,
  spotlightId,
  handleItemFocus,
  handleShelfFocus,
  shelfLocation,
  shelfTitle,
  ...rest
}) => {
  const { getScrollTo, scrollLeft } = useScrollTo();
  const { handleScrollReset, handleStopScrolling } = useScrollReset(
    scrollLeft,
    true
  );

  const dispatch = useDispatch();

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

  const topInfos = useSelector((state) => state.main.top20ShowData.topInfos);

  const [drawChk, setDrawChk] = useState(false);

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

  const [firstChk, setFirstChk] = useState(0);

  useEffect(() => {
    setDrawChk(true);
  }, [topInfos]);

  const handleCardClick = useCallback(
    (patnrId, showId, catCd, showUrl) => () => {
      dispatch(
        startVideoPlayer({
          showId,
          patnrId,
          shptmBanrTpNm: "VOD",
          lgCatCd: catCd,
          modal: false,
          showUrl: showUrl,
        })
      );
    },
    [dispatch]
  );

  const handleMoreCardClick = useCallback(() => {
    dispatch(
      pushPanel(
        {
          name: panel_names.TRENDING_NOW_PANEL,
          panelInfo: {
            pageName: "PS",
            focusedContainerId: SpotlightIds.TRENDING_NOW_POPULAR_SHOW,
          },
        },
        [dispatch]
      )
    );
  });

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

  const handleFocus = useCallback(
    (itemIndex) => () => {
      _handleItemFocus();

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

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

      if (cursorVisible) {
        return;
      }
    },
    [
      cursorVisible,
      _handleItemFocus,
      handleScrollReset,
      scrollTopBody,
      firstChk,
    ]
  );

  const handleScrollRight = (e) => {
    const container = e.currentTarget?.parentNode;
    const x = container.scrollWidth - container.clientWidth + 60;

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

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

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

  return (
    <Container
      className={css.popularShow}
      style={orderStyle}
      spotlightId={spotlightId}
      data-wheel-point={true}
      onFocus={_handleShelfFocus}
    >
      <SectionTitle
        className={css.subTitle}
        title={$L("POPULAR SHOW")}
        data-title-index="homePopularShow"
        label="POPULAR SHOW"
      />
      <TScroller
        className={css.showList}
        direction="horizontal"
        cbScrollTo={getScrollTo}
        noScrollByWheel
      >
        {topInfos &&
          topInfos.map(
            (
              {
                showId,
                thumbnailUrl,
                thumbnailUrl960,
                showNm,
                vtctpYn,
                patncLogoPath,
                catNm,
                patnrId,
                patncNm,
                catCd,
                showUrl,
              },
              itemIndex
            ) => {
              return (
                <TItemCard
                  key={showId}
                  contextName={LOG_CONTEXT_NAME.HOME}
                  messageId={LOG_MESSAGE_ID.SHELF_CLICK}
                  catNm={catNm}
                  order={itemIndex + 1}
                  shelfId={spotlightId}
                  shelfLocation={shelfLocation}
                  shelfTitle={shelfTitle}
                  patnerName={patncNm}
                  showId={showId}
                  showTitle={showNm}
                  imageSource={
                    thumbnailUrl !== thumbnailUrl960
                      ? thumbnailUrl960
                      : thumbnailUrl
                  }
                  imageAlt={showNm}
                  productName={showNm}
                  nonPosition={true}
                  type={TYPES.videoShow}
                  imgType={
                    vtctpYn !== "Y"
                      ? IMAGETYPES.imgHorizontal
                      : IMAGETYPES.imgVertical
                  }
                  logo={patncLogoPath}
                  productId={showId}
                  onFocus={handleFocus(itemIndex)}
                  onBlur={handleBlur(itemIndex)}
                  onClick={handleCardClick(patnrId, showId, catCd, showUrl)}
                  firstLabel={patncNm + " "}
                  label={itemIndex * 1 + 1 + " of " + topInfos.length}
                  lastLabel=" go to detail, button"
                />
              );
            }
          )}

        {drawChk && homeChk === true && (
          <div className={css.addItem} onFocus={handleScrollRight}>
            <SpottableComponent
              className={css.displayBox}
              onClick={handleMoreCardClick}
              onFocus={_handleItemFocus}
              spotlightId={"home-popularshow-more-btn"}
            ></SpottableComponent>
          </div>
        )}
      </TScroller>
    </Container>
  );
};

export default PopularShow;
