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

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

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

import { pushPanel } from "../../../../actions/panelActions";
import { startVideoPlayer } from "../../../../actions/playActions";
import useScrollReset from "../../../../hooks/useScrollReset";
import useScrollTo from "../../../../hooks/useScrollTo";
import {
  LOG_CONTEXT_NAME,
  LOG_MESSAGE_ID,
  panel_names,
} from "../../../../utils/Config";
import { $L } from "../../../../utils/helperMethods";
import MyPageItemCard from "../../MyPageItemCard/MyPageItemCard";
import css from "../RecentlyViewed/RecentlyViewedContents.module.less";
import { sendLogTotalRecommend } from "../../../../actions/logActions";

const ContainerBasic = SpotlightContainerDecorator({ enterTo: null }, "div");
export default function RecentlyViewedContents({
  indexNo,
  title,
  dataSize,
  recentDataInfoItem,
  activeDelete,
  selectedItems,
  handleItemToggle,
  selectedPatnrId,
  firstSpot,
}) {
  const dispatch = useDispatch();
  const { scrollLeft } = useScrollTo();
  const containerRef = useRef(null);

  const today = `${new Date().getMonth() + 1}/${new Date().getDate()}`;

  const mainContainerId = useMemo(() => {
    return "recently-product-list-id-" + recentDataInfoItem?.date;
  }, [recentDataInfoItem]);

  useEffect(() => {
    const container = document.getElementById(mainContainerId);

    if (container) {
      const firstChild = container.querySelector(".container > *");

      if (firstChild) {
        const childrenId = getContainerId(firstChild);

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

    scrollLeft();
  }, [mainContainerId, recentDataInfoItem, scrollLeft]);

  const handleItemClick = useCallback(
    (showId, showNm, patnrId, lgCatCd, prdtId, prdtNm, patncNm, brndNm) =>
      () => {
        const params = {
          menu: "Recently Viewed",
          partner: patncNm,
          contentId: showId,
          contentTitle: showNm,
          productId: prdtId,
          productTitle: prdtNm,
          showId: showId,
          showTitle: showNm,
          brand: brndNm,
          contextName: LOG_CONTEXT_NAME.MYPAGE,
          messageId: LOG_MESSAGE_ID.MYPAGE_CLICK,
        };
        dispatch(sendLogTotalRecommend(params));

        if (showId) {
          dispatch(
            startVideoPlayer({
              showId,
              patnrId,
              shptmBanrTpNm: "VOD",
              lgCatCd,
              modal: false,
            })
          );
        } else {
          dispatch(
            pushPanel({
              name: panel_names.DETAIL_PANEL,
              panelInfo: { patnrId, prdtId },
            })
          );
        }
      },
    [recentDataInfoItem]
  );
  const _handleItemToggle = useCallback(
    (showId, prdtId) => () => {
      if (handleItemToggle) {
        handleItemToggle(prdtId ? prdtId : showId);
      }
    },
    [handleItemToggle]
  );

  return (
    <ContainerBasic
      className={css.recentDataWrap}
      id={mainContainerId}
      data-title-index={"mypage-recently-viewed-" + indexNo}
      spotlightId={"mypage-recently-viewed-" + indexNo}
      data-wheel-point={true}
      ref={containerRef}
    >
      {dataSize > 0 && (
        <h3
          data-subtitle={title}
          aria-label={
            title === today ? "Today, Heading 2" : title + ", Heading 3"
          }
        >
          {title === today ? $L("Today") : title}
        </h3>
      )}
      <ContainerBasic className={css.container}>
        {recentDataInfoItem &&
          dataSize > 0 &&
          recentDataInfoItem.productInfos.map((item, index) => {
            const {
              imgUrl,
              patnrId,
              showId,
              prdtId,
              prdtNm,
              patncNm,
              soldOutYn,
              lgCatCd,
              thumbnailUrl,
              showNm,
            } = item;
            return (
              <MyPageItemCard
                key={`${prdtId ? prdtId : showId}-${patnrId}`}
                thumbnail={prdtId ? imgUrl : thumbnailUrl}
                title={prdtId ? prdtNm : showNm}
                soldOutYn={soldOutYn}
                activeDelete={activeDelete}
                selected={selectedItems[prdtId ? prdtId : showId]}
                onClick={handleItemClick(
                  showId,
                  showNm,
                  patnrId,
                  lgCatCd,
                  prdtId,
                  prdtNm,
                  patncNm
                )}
                onToggle={_handleItemToggle(showId, prdtId)}
                spotlightId={mainContainerId + index}
                dataWheelPoint={index >= 5}
              />
            );
          })}
      </ContainerBasic>
    </ContainerBasic>
  );
}
