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

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

import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import Spottable from "@enact/spotlight/Spottable";
import Marquee from "@enact/ui/Marquee";

import defaultLogoImg from "../../../../assets/images/ic-tab-partners-default@3x.png";
import { setShowPopup } from "../../../actions/commonActions";
import CustomImage from "../../../components/CustomImage/CustomImage";
import { ACTIVE_POPUP } from "../../../utils/Config";
import { SpotlightIds } from "../../../utils/SpotlightIds";
import PlayerTabButton from "../PlayerTabContents/TabButton/PlayerTabButton";
import css from "./PlayerOverlayContents.module.less";

const SpottableBtn = Spottable("button");

const Container = SpotlightContainerDecorator(
  { enterTo: "default-element" },
  "div"
);

export default function PlayerOverlayContents({
  type,
  onClick,
  panelInfo,
  disclaimer,
  playListInfo,
  captionEnable,
  selectedIndex,
  setIsSubtitleActive,
  videoVerticalVisible,
  sideContentsVisible,
  setSideContentsVisible,
  handleIndicatorUpClick,
  handleIndicatorDownClick,
  ...rest
}) {
  const cntry_cd = useSelector((state) => state.common.httpHeader?.cntry_cd);
  const dispatch = useDispatch();
  const onClickBack = (ev) => {
    if (onClick) {
      onClick(ev);
    }
  };
  const backBtnRef = useRef(null);

  useEffect(() => {
    if (type === "MEDIA" && !panelInfo.modal && backBtnRef.current) {
      Spotlight.focus(SpotlightIds.PLAYER_BACK_BUTTON);
    }
  }, [panelInfo?.shptmBanrTpNm, panelInfo.modal, backBtnRef.current]);

  const handleSubtitleOnClick = useCallback(() => {
    if (!captionEnable) {
      return dispatch(setShowPopup(ACTIVE_POPUP.alertPopup));
    }

    setIsSubtitleActive((prev) => !prev);
  }, [captionEnable]);

  const patncLogoPath = useMemo(() => {
    let logo = playListInfo[selectedIndex]?.patncLogoPath
      ? playListInfo[selectedIndex]?.patncLogoPath
      : playListInfo[selectedIndex]?.logoImgPath;
    if (type === "MEDIA") {
      logo = panelInfo?.patncLogoPath;
    }

    return logo;
  }, [playListInfo, selectedIndex, panelInfo]);

  const partnerName = useMemo(() => {
    let name = playListInfo[selectedIndex]?.patncNm;
    if (type === "MEDIA") {
      name = panelInfo?.patncNm;
    }

    return name;
  }, [playListInfo, selectedIndex, panelInfo]);

  const showName = useMemo(() => {
    let name = playListInfo[selectedIndex]?.showNm;
    if (type === "MEDIA") {
      name = panelInfo?.showNm;
    }

    return name ? name.replace(/<br\s*\/?>/gi, " ") : "";
  }, [playListInfo, selectedIndex, panelInfo]);

  const onSpotlightMoveTabButton = (e) => {
    e.stopPropagation();
    e.preventDefault();
    Spotlight.focus(SpotlightIds.PLAYER_TAB_BUTTON);
  };

  const onSpotlightMoveMediaButton = (e) => {
    e.stopPropagation();
    if (type === "LIVE") {
      return Spotlight.focus("videoIndicator-down-button");
    }
    Spotlight.focus("videoPlayer_mediaControls");
  };

  const onSpotlightMoveSlider = useCallback(
    (e) => {
      if (type === "VOD") {
        e.stopPropagation();

        Spotlight.focus(SpotlightIds.PLAYER_SLIDER);
      }
    },
    [panelInfo]
  );

  const onSpotlightMoveSideTab = (e) => {
    e.stopPropagation();
    e.preventDefault();
    Spotlight.focus("tab-0");
  };

  const onSpotlightMoveBackButton = () => {
    return Spotlight.focus(SpotlightIds.PLAYER_BACK_BUTTON);
  };

  const currentSideButtonStatus = useMemo(() => {
    if (type !== "MEDIA" && !panelInfo?.modal && !sideContentsVisible) {
      return true;
    }
    return false;
  }, [panelInfo, sideContentsVisible]);

  const noLiveContentsVisible = useMemo(() => {
    if (!Array.isArray(playListInfo) || playListInfo.length === 0) {
      return false;
    }

    const noShowIdCount = playListInfo.filter((item) => !item.showId).length;
    if (playListInfo.length - 1 === noShowIdCount) {
      return false;
    }

    return true;
  }, [playListInfo]);

  return (
    <>
      <Container className={css.overlayContainer}>
        {type !== "MEDIA" &&
          playListInfo.length > 1 &&
          noLiveContentsVisible && (
            <>
              <div className={css.indicatorUpButton}>
                <SpottableBtn
                  onClick={handleIndicatorUpClick}
                  spotlightId="videoIndicator-up-button"
                  onSpotlightRight={
                    videoVerticalVisible
                      ? onSpotlightMoveSideTab
                      : onSpotlightMoveTabButton
                  }
                  onSpotlightDown={onSpotlightMoveSlider}
                  aria-label="Previous channel"
                />
              </div>
              <div className={css.indicatorDownButton}>
                <SpottableBtn
                  onClick={handleIndicatorDownClick}
                  spotlightId="videoIndicator-down-button"
                  onSpotlightLeft={onSpotlightMoveSlider}
                  onSpotlightUp={onSpotlightMoveSlider}
                  onSpotlightRight={
                    videoVerticalVisible
                      ? onSpotlightMoveSideTab
                      : onSpotlightMoveSlider
                  }
                  aria-label="Next channel"
                />
              </div>
            </>
          )}

        {currentSideButtonStatus && !videoVerticalVisible && (
          <PlayerTabButton
            setSideContentsVisible={setSideContentsVisible}
            sideContentsVisible={sideContentsVisible}
            onSpotlightLeft={
              type !== "MEDIA" &&
              playListInfo.length < 2 &&
              onSpotlightMoveBackButton
            }
            videoType={type}
          />
        )}

        {cntry_cd === "US" && (
          <div className={css.videoButtonContainer}>
            <SpottableBtn
              className={classNames(
                css.subtitleButton,
                videoVerticalVisible && css.videoVericalSubtitleButton
              )}
              onClick={handleSubtitleOnClick}
              spotlightId="player-subtitlebutton"
              onSpotlightUp={onSpotlightMoveTabButton}
              onSpotlightLeft={onSpotlightMoveMediaButton}
              aria-label="Caption"
            />
          </div>
        )}
        <div className={css.overlayHeader}>
          <SpottableBtn
            onClick={onClickBack}
            className={css.backIcon}
            spotlightId="player-back-button"
            onSpotlightDown={onSpotlightMoveMediaButton}
            aria-label="Video Player Close"
            ref={backBtnRef}
          />
          <div
            className={classNames(type === "LIVE" && css.liveIcon)}
            aria-label={type === "LIVE" && "Live Icon"}
          />

          {partnerName && (
            <CustomImage
              src={patncLogoPath}
              fallbackSrc={defaultLogoImg}
              alt={partnerName}
              aria-label={partnerName}
            />
          )}

          <h2 className={css.patnerName}>{partnerName}</h2>

          <Marquee
            className={classNames(
              css.title,
              videoVerticalVisible && css.videoVerticalMarquee
            )}
            marqueeOn="render"
          >
            {showName}
          </Marquee>
        </div>
      </Container>
      {type === "VOD" && disclaimer && (
        <div className={css.disclaimer}>
          <span className={css.icon} />
          <h3 aria-label={disclaimer}>{disclaimer}</h3>
        </div>
      )}
    </>
  );
}
