import React, {
  useCallback,
  useEffect,
  useMemo,
  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_3.module.less";

const SpottableComponent = Spottable("li");
const SpottableComponentDiv = Spottable("div");

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

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

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

  const [videoFocused, setVideoFocused] = useState(false);

  const videoFocusedRef = usePrevious(videoFocused);

  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_3",
          })
        );
      });
    } else {
      dispatch(finishVideoPreview());
    }

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

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

  const getBackgroundStyle = useCallback((bgImgPath) => {
    return bgImgPath ? { backgroundImage: `url(${bgImgPath})` } : {};
  }, []);

  return (
    <>
      {data &&
        data.map(
          ({
            tmpltCd,
            productInfos,
            showInfos,
            hotelInfos,
            bgImgPath,
            showEffectiveFlag,
          }) => {
            return (
              <div
                key={tmpltCd}
                className={classNames(className && className, css.flexCont)}
                style={
                  showEffectiveFlag === "N"
                    ? getBackgroundStyle(bgImgPath)
                    : null
                }
              >
                <div className={css.fullImg}>
                  {showInfos &&
                    showInfos
                      .slice(0, 1)
                      .map(({ showId, showNm, thumbnailUrl }) => {
                        // @@@ 영상 출력 처리
                        return (
                          <SpottableComponentDiv
                            key={showId}
                            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}
                            />
                          </SpottableComponentDiv>
                        );
                      })}
                </div>
                <Container className={css.itemList}>
                  {productInfos &&
                    productInfos
                      .slice(0, 3)
                      .map(({ imgUrl, prdtNm, prdtId }, index) => {
                        return (
                          <SpottableComponent
                            key={prdtId}
                            onClick={() => {
                              handleItemClick(prdtId);
                            }}
                            spotlightId={spotName + "_" + index}
                            onSpotlightDown={
                              productInfos.length >= 3
                                ? index === 2
                                  ? _onSpotlightDown
                                  : null
                                : productInfos.length === 2
                                ? index === 1
                                  ? _onSpotlightDown
                                  : null
                                : _onSpotlightDown
                            }
                            onSpotlightUp={index === 0 ? _onSpotlightUp : null}
                            index={index}
                            aria-label={
                              "selected " +
                              prdtNm +
                              " " +
                              index * 1 +
                              1 +
                              " of 3"
                            }
                          >
                            <CustomImage
                              delay={0}
                              animationSpeed="fast"
                              src={imgUrl}
                              fallbackSrc={defaultImageItem}
                              alt={prdtNm}
                              ariaLabel={
                                "selected " +
                                prdtNm +
                                " " +
                                index * 1 +
                                1 +
                                " of 3"
                              }
                            />
                          </SpottableComponent>
                        );
                      })}
                  {hotelInfos &&
                    hotelInfos
                      .slice(0, 3)
                      .map(({ hotelImgUrl, hotelNm, hotelId }, index) => {
                        return (
                          <SpottableComponent
                            key={hotelId}
                            onClick={() => {
                              handleHotelClick(hotelId);
                            }}
                            spotlightId={spotName + "_" + index}
                            onSpotlightDown={
                              hotelInfos.length >= 3
                                ? index === 2
                                  ? _onSpotlightDown
                                  : null
                                : hotelInfos.length === 2
                                ? index === 1
                                  ? _onSpotlightDown
                                  : null
                                : hotelInfos.length === 1
                                ? index === 0
                                  ? _onSpotlightDown
                                  : null
                                : null
                            }
                            onSpotlightUp={index === 0 ? _onSpotlightUp : null}
                            index={index}
                            aria-label={
                              "selected " +
                              hotelNm +
                              " " +
                              index * 1 +
                              1 +
                              " of 3"
                            }
                          >
                            <CustomImage
                              delay={0}
                              animationSpeed="fast"
                              src={hotelImgUrl}
                              fallbackSrc={defaultImageItem}
                              alt={hotelNm}
                              ariaLabel={
                                "selected " +
                                hotelNm +
                                " " +
                                index * 1 +
                                1 +
                                " of 3"
                              }
                            />
                          </SpottableComponent>
                        );
                      })}
                </Container>
              </div>
            );
          }
        )}
    </>
  );
}
