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

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

import { Job } from "@enact/core/util";
import Spotlight from "@enact/spotlight";

import { updatePanel } from "../../../../../actions/panelActions";
import { startVideoPlayer } from "../../../../../actions/playActions";
import TItemCard, {
  removeDotAndColon,
  TYPES,
} from "../../../../../components/TItemCard/TItemCard";
import TVirtualGridList from "../../../../../components/TVirtualGridList/TVirtualGridList";
import useScrollTo from "../../../../../hooks/useScrollTo";
import {
  LOG_CONTEXT_NAME,
  LOG_MESSAGE_ID,
  panel_names,
} from "../../../../../utils/Config";
import {
  getTranslate3dValueByDirection,
  scaleH,
} from "../../../../../utils/helperMethods";
import css from "./LiveChannelsVerticalProductList.module.less";

export default function LiveChannelsVerticalProductList({
  brandProductInfo,
  chanId,
  handleItemFocus,
  patnrId,
  selectedPatnrId,
  showId,
  showNm,
  showUrl,
  catNm,
  patnerName,
  shelfOrder,
  shelfTitle,
  spotlightId,
  liveYn,
}) {
  const { getScrollTo, scrollTop } = useScrollTo();

  const dispatch = useDispatch();

  const panelInfo = useSelector((state) => state.panels.panels[0]?.panelInfo);

  const scrollTopJob = useRef(new Job((func) => func(), 0));

  useEffect(() => {
    if (panelInfo?.section !== "live-channels-vertical" || !panelInfo?.v) {
      return;
    }

    const scrollTopJobValue = scrollTopJob.current;
    const { v } = panelInfo;

    scrollTopJobValue.start(() => scrollTop({ y: v, animate: false }));

    return () => scrollTopJobValue.stop();
  }, [panelInfo, scrollTop]);

  useEffect(() => {
    scrollTop({ animate: false });
  }, [scrollTop, selectedPatnrId]);

  const handleClick = useCallback(
    (prdtId, index) => (e) => {
      const tItemCard = e.currentTarget;

      const lastFocusedTarget = Spotlight.getCurrent();
      const lastFocusedTargetId =
        lastFocusedTarget?.getAttribute("data-spotlight-id");

      const vContainer = tItemCard?.parentNode?.parentNode;

      if (lastFocusedTargetId && vContainer) {
        const section = "live-channels-vertical";
        const v = getTranslate3dValueByDirection(vContainer, false);
        const x = 0;

        dispatch(
          updatePanel({
            name: panel_names.FEATURED_BRANDS_PANEL,
            panelInfo: {
              lastFocusedTargetId,
              patnrId,
              section,
              v,
              x,
            },
          })
        );
      }

      let y =
        index < 2
          ? 0
          : index === 2
          ? scaleH(208)
          : scaleH(index * 248 - 248 - 40);

      dispatch(
        startVideoPlayer({
          chanId,
          modal: false,
          patnrId,
          showId,
          showUrl,
          shptmBanrTpNm: liveYn === "Y" ? "LIVE" : "VOD",
          targetId: "spotlightId-" + prdtId,
          y,
        })
      );
    },
    [chanId, dispatch, patnrId, showId, showUrl]
  );

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

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const {
        offerInfo, //
        prdtId,
        prdtImgUrl,
        prdtNm,
        priceInfo,
        soldoutFlag,
        brndNm,
      } = brandProductInfo[index];

      return (
        <TItemCard
          contextName={LOG_CONTEXT_NAME.FEATURED_BRANDS}
          messageId={LOG_MESSAGE_ID.SHELF_CLICK}
          order={index + 1}
          brandName={brndNm}
          catNm={catNm}
          contentId={showId}
          contentTitle={showNm}
          patnerName={patnerName}
          shelfId={spotlightId}
          shelfLocation={shelfOrder}
          shelfTitle={shelfTitle}
          imageAlt={prdtNm}
          imageSource={prdtImgUrl}
          onClick={handleClick(prdtId, index)}
          onFocus={handleFocus}
          offerInfo={offerInfo}
          priceInfo={priceInfo}
          productId={prdtId}
          productName={prdtNm}
          soldoutFlag={soldoutFlag}
          spotlightId={"live-channels-spotlightId-" + removeDotAndColon(prdtId)}
          type={TYPES.horizontal}
          label={index * 1 + 1 + " of " + brandProductInfo.length}
          lastLabel=" go to detail, button"
          {...rest}
        />
      );
    },
    [brandProductInfo, handleClick, handleFocus]
  );

  return (
    <div className={css.container}>
      {brandProductInfo && (
        <TVirtualGridList
          cbScrollTo={getScrollTo}
          className={css.tVirtualGridList}
          dataSize={brandProductInfo.length}
          itemHeight={236}
          itemWidth={660}
          spacing={12}
          renderItem={renderItem}
        />
      )}
    </div>
  );
}
