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

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

import { Job } from "@enact/core/util";
import Spotlight from "@enact/spotlight";
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.module.less";

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

export default function TCFV({
  className,
  data,
  orders,
  onSpotlightDown,
  onSpotlightUp,
  currentPage,
  onItemClick,
  sendLogClick,
  mobilePop,
  changePop,
  eventInfo,
  osVersion,
  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 videoSpotName = spotName + 0;
  const bgImgNm = data && data[0].bgImgNo !== null ? data[0].bgImgNo : null;
  let typeChk = data && data[0].hotelInfos?.length !== 0 ? "hotel" : "theme";

  const handleItemClick = () => {
    dispatch(finishVideoPreview());
    if (onItemClick) {
      onItemClick();
    }
    if (sendLogClick) {
      sendLogClick();
    }
    if (osVersion === false) {
      if (mobilePop !== "Y") {
        dispatch(
          pushPanel({
            name: panel_names.DETAIL_PANEL,
            panelInfo: {
              patnrId: data[0].patnrId,
              prdtId: data[0].productInfos[0].prdtId,
              curationId: data[0].curationId,
              curationNm: data[0].curationNm,
              bgImgNo: bgImgNm,
              type: typeChk,
            },
          })
        );
      } else {
        changePop(
          data[0].patnrId,
          data[0].curationId,
          data[0].evntId,
          data[0].evntTpCd,
          data[0].eventInfoV2
        );
      }
    } else {
      if (eventInfo !== null) {
        changePop(
          data[0].patnrId,
          data[0].curationId,
          data[0].evntId,
          data[0].evntTpCd,
          data[0].eventInfoV2
        );
      } else {
        if (mobilePop !== "Y") {
          dispatch(finishVideoPreview());
          dispatch(
            pushPanel({
              name: panel_names.DETAIL_PANEL,
              panelInfo: {
                patnrId: data[0].patnrId,
                prdtId: data[0].productInfos[0].prdtId,
                curationId: data[0].curationId,
                curationNm: data[0].curationNm,
                type: typeChk,
              },
            })
          );
        } else {
          changePop(
            data[0].patnrId,
            data[0].curationId,
            data[0].evntId,
            data[0].evntTpCd,
            data[0].eventInfoV2
          );
        }
      }
    }
  };

  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: videoSpotName, //to calc width, height, left, top
        modalClassName: css.videoModal,
        spotlightDisable: false,
      })
    );
  }, [data, dispatch, videoSpotName]);

  const _onSpotlightDown = useCallback(
    (ev) => {
      ev.stopPropagation();

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

      if (onSpotlightUp) {
        onSpotlightUp(ev);
      }
    },
    [onSpotlightUp]
  );

  const _onSpotlightRight = useCallback((ev) => {
    ev.stopPropagation();
    Spotlight.focus(spotName);
  }, []);
  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: videoSpotName, //to calc width, height, left, top
            modalClassName: modalClassNameChange(),
            spotlightDisable: true,
            hotPicksType: "TCFV",
          })
        );
        Spotlight.focus(videoSpotName);
      });
    } else {
      dispatch(finishVideoPreview());
    }

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

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

  return (
    <>
      {data &&
        data.map(({ bgImgPath, curationNm, tmpltCd, showInfos }) => {
          return (
            <Container
              key={tmpltCd + curationNm}
              className={classNames(className && className)}
            >
              <SpottableComponentDiv
                className={css.fullImg}
                spotlightId={spotName}
                onClick={handleItemClick}
                onSpotlightDown={_onSpotlightDown}
                onSpotlightUp={_onSpotlightUp}
              >
                <CustomImage
                  delay={0}
                  animationSpeed="fast"
                  src={bgImgPath}
                  fallbackSrc={defaultImageItem}
                  alt={curationNm}
                  ariaLabel={curationNm}
                />
              </SpottableComponentDiv>
              <ul className={css.itemList}>
                {showInfos &&
                  showInfos.slice(0, 1).map(({ showNm, thumbnailUrl }) => {
                    // @@@ 영상 출력 처리
                    return (
                      <SpottableComponent
                        key={showNm + thumbnailUrl}
                        onClick={handleVideoClick}
                        className={css.videoBox}
                        spotlightId={videoSpotName}
                        onFocus={onVideoFocus}
                        onBlur={onVideoBlur}
                        aria-label={"selected " + showNm}
                        onSpotlightRight={_onSpotlightRight}
                        onSpotlightDown={_onSpotlightDown}
                        onSpotlightUp={_onSpotlightUp}
                      >
                        <CustomImage
                          delay={0}
                          animationSpeed="fast"
                          src={thumbnailUrl}
                          fallbackSrc={defaultImageItem}
                          alt={showNm}
                          ariaLabel={"selected " + showNm}
                        />
                      </SpottableComponent>
                    );
                  })}
              </ul>
            </Container>
          );
        })}
    </>
  );
}
