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

import classNames from "classnames";
import { useDispatch } from "react-redux";

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

import defaultImageItem from "../../../../../assets/images/img-thumb-empty-product@3x.png";
import { pushPanel, updatePanel } from "../../../../actions/panelActions";
import {
  finishVideoPreview,
  startVideoPlayer,
} from "../../../../actions/playActions";
import CustomImage from "../../../../components/CustomImage/CustomImage";
import usePrevious from "../../../../hooks/usePrevious";
import { panel_names } from "../../../../utils/Config";
import css from "./TCFV_4.module.less";

const ContainerTCFV = SpotlightContainerDecorator(
  {
    enterTo: "last-focused",
    leaveFor: { right: "", down: "" },
  },
  "ul"
);

const SpottableComponent = Spottable("li");

export default function TCFV_4({
  className,
  data,
  orders,
  onSpotlightDown,
  onSpotlightUp,
  currentPage,
  sendLogClick,
  scrolling = false,
}) {
  const dispatch = useDispatch();

  const [videoFocused, setVideoFocused] = useState(false);
  const videoFocusedRef = usePrevious(videoFocused);
  const playingJob = useRef(new Job((func) => func(), 0));

  const spotName = "hotpicks-data-spot" + orders;

  const handleItemClick = (prdtId) => {
    if (sendLogClick) {
      sendLogClick();
    }
    dispatch(finishVideoPreview());
    dispatch(
      pushPanel({
        name: panel_names.DETAIL_PANEL,
        panelInfo: {
          patnrId: data[0].patnrId,
          themePrdtId: prdtId,
          prdtId: prdtId,
          curationId: data[0].curationId,
          curationNm: data[0].curationNm,
          type: "theme",
        },
      })
    );
  };

  const handleHotelClick = (hotelId) => {
    if (sendLogClick) {
      sendLogClick();
    }
    dispatch(finishVideoPreview());
    dispatch(
      pushPanel({
        name: panel_names.DETAIL_PANEL,
        panelInfo: {
          patnrId: data[0].patnrId,
          themeHotelId: hotelId,
          curationId: data[0].curationId,
          curationNm: data[0].curationNm,
          type: "hotel",
        },
      })
    );
  };

  const handleVideoClick = useCallback(() => {
    if (sendLogClick) {
      sendLogClick();
    }
    dispatch(
      startVideoPlayer({
        showId: data[0].showId,
        showUrl: data[0].showUrl,
        showNm: data[0].showNm,
        patncNm: data[0].patncNm,
        patnrId: data[0].patnrId,
        patncLogoPath: data[0].patncLogoPath,
        orderPhnNo: data[0].orderPhnNo,
        shptmBanrTpNm: "MEDIA",
        modal: false,
        modalContainerId: spotName, //to calc width, height, left, top
        modalClassName: css.videoModal,
        spotlightDisable: false,
      })
    );
  }, [data, dispatch, spotName]);

  const _onSpotlightDown = useCallback((ev) => {
    ev.stopPropagation();
    ev.preventDefault();
    onSpotlightDown(ev);
  }, []);

  const _onSpotlightUp = useCallback((ev) => {
    ev.stopPropagation();
    ev.preventDefault();
    onSpotlightUp(ev);
  }, []);

  const modalClassNameChange = useCallback(() => {
    if (videoFocusedRef.current) {
      return css.videoModal;
    } else {
      return "";
    }
  }, []);

  const onVideoFocus = useCallback(() => {
    setVideoFocused(true);
  }, []);

  const onVideoBlur = useCallback(() => {
    setVideoFocused(false);
  }, []);

  useEffect(() => {
    const playingJobValue = playingJob.current;

    if (currentPage === orders - 1 && !scrolling) {
      playingJobValue.start(() => {
        dispatch(
          startVideoPlayer({
            showId: data[0].showId,
            showUrl: data[0].showUrl,
            showNm: data[0].showNm,
            patncNm: data[0].patncNm,
            patnrId: data[0].patnrId,
            patncLogoPath: data[0].patncLogoPath,
            orderPhnNo: data[0].orderPhnNo,
            shptmBanrTpNm: "MEDIA",
            modal: true,
            modalContainerId: spotName, //to calc width, height, left, top
            modalClassName: modalClassNameChange(),
            spotlightDisable: true,
            hotPicksType: "TCFV_4",
          })
        );
      });
    } else {
      dispatch(finishVideoPreview());
    }

    return () => {
      playingJobValue.stop();
    };
  }, [dispatch, orders, currentPage, spotName, scrolling]);

  useEffect(() => {
    dispatch(
      updatePanel({
        name: panel_names.PLAYER_PANEL,
        panelInfo: {
          modalClassName: modalClassNameChange(),
        },
      })
    );
  }, [videoFocused, dispatch]);

  return (
    <>
      {data &&
        data.map(
          ({
            bgImgPath,
            curationNm,
            tmpltCd,
            productInfos,
            showInfos,
            hotelInfos,
          }) => {
            return (
              <div key={tmpltCd} className={classNames(className && className)}>
                <div className={css.fullImg}>
                  <CustomImage
                    src={bgImgPath}
                    animationSpeed="fast"
                    fallbackSrc={defaultImageItem}
                    alt={curationNm}
                    ariaLabel={curationNm}
                  />
                </div>
                <ContainerTCFV className={css.itemList}>
                  {showInfos &&
                    showInfos
                      .slice(0, 1)
                      .map(({ showId, showNm, thumbnailUrl }, index) => {
                        // @@@ 영상 출력 처리
                        return (
                          <SpottableComponent
                            key={showId + index}
                            spotlightId={spotName}
                            onSpotlightDown={_onSpotlightDown}
                            onSpotlightUp={_onSpotlightUp}
                            onClick={handleVideoClick}
                            className={css.videoBox}
                            onFocus={onVideoFocus}
                            onBlur={onVideoBlur}
                            aria-label={"selected " + showNm}
                          >
                            <CustomImage
                              delay={0}
                              animationSpeed="fast"
                              src={thumbnailUrl}
                              fallbackSrc={defaultImageItem}
                              alt={showNm}
                              ariaLabel={"selected " + showNm}
                            />
                          </SpottableComponent>
                        );
                      })}
                  {productInfos &&
                    productInfos
                      .slice(0, 4)
                      .map(({ imgUrl, prdtNm, prdtId }, index) => {
                        return (
                          <SpottableComponent
                            key={prdtId + index}
                            onSpotlightDown={_onSpotlightDown}
                            onSpotlightUp={_onSpotlightUp}
                            spotlightId={spotName + "_" + index}
                            onClick={() => {
                              handleItemClick(prdtId);
                            }}
                            index={index}
                            aria-label={
                              "selected " +
                              prdtNm +
                              " " +
                              index * 1 +
                              1 +
                              " of 4"
                            }
                          >
                            <CustomImage
                              delay={0}
                              animationSpeed="fast"
                              src={imgUrl}
                              fallbackSrc={defaultImageItem}
                              alt={prdtNm}
                              ariaLabel={
                                "selected " +
                                prdtNm +
                                " " +
                                index * 1 +
                                1 +
                                " of 4"
                              }
                            />
                          </SpottableComponent>
                        );
                      })}
                  {hotelInfos &&
                    hotelInfos
                      .slice(0, 4)
                      .map(({ hotelImgUrl, hotelNm, hotelId }, index) => {
                        return (
                          <SpottableComponent
                            key={hotelId}
                            onSpotlightDown={_onSpotlightDown}
                            onSpotlightUp={_onSpotlightUp}
                            onClick={() => {
                              handleHotelClick(hotelId);
                            }}
                            spotlightId={spotName + "_" + index}
                            type="hotelInfo"
                            index={index}
                            aria-label={
                              "selected " +
                              hotelNm +
                              " " +
                              index * 1 +
                              1 +
                              " of 4"
                            }
                          >
                            <CustomImage
                              delay={0}
                              animationSpeed="fast"
                              src={hotelImgUrl}
                              fallbackSrc={defaultImageItem}
                              alt={hotelNm}
                              ariaLabel={
                                "selected " +
                                hotelNm +
                                " " +
                                index * 1 +
                                1 +
                                " of 4"
                              }
                            />
                          </SpottableComponent>
                        );
                      })}
                </ContainerTCFV>
              </div>
            );
          }
        )}
    </>
  );
}
