import React, { useCallback, useEffect } 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 { updatePanel } from "../../../../actions/panelActions";
import { panel_names } from "../../../../utils/Config";
import { SpotlightIds } from "../../../../utils/SpotlightIds";
import css from "./PlayerTabButton.module.less";

const SpottableComponent = Spottable("button");
const Container = SpotlightContainerDecorator(
  { enterTo: "default-element", preserveld: true },
  "div"
);
export default function PlayerTabButton({
  sideContentsVisible,
  setSideContentsVisible,
  onSpotlightLeft,
  videoType,
}) {
  const dispatch = useDispatch();
  const countryCode = useSelector((state) => state.common.httpHeader.cntry_cd);

  const handleTabOnClick = (e) => {
    dispatch(
      updatePanel({
        name: panel_names.PLAYER_PANEL,
        panelInfo: {
          isUpdatedByClick: false,
        },
      })
    );
    setSideContentsVisible((prev) => !prev);
    setTimeout(() => {
      Spotlight.focus(SpotlightIds.PLAYER_TAB_BUTTON);
    }, 0);

    e.stopPropagation();
  };

  const _onSpotlightLeft = useCallback(
    (e) => {
      if (onSpotlightLeft) {
        // e.stopPropagation();
        onSpotlightLeft();
        return;
      }
      if (!sideContentsVisible) {
        e.stopPropagation();
        Spotlight.focus("videoIndicator-up-button");
      }
    },
    [sideContentsVisible]
  );

  const onSpotlightDown = useCallback(
    (e) => {
      if (countryCode !== "US") {
        if (videoType === "VOD") {
          Spotlight.focus("videoIndicator-up-button");
        } else if (videoType === "LIVE") {
          Spotlight.focus(SpotlightIds.PLAYER_SLIDER);
        }
        return;
      }
      if (!sideContentsVisible) {
        e.stopPropagation();
        Spotlight.focus(SpotlightIds.PLAYER_SUBTITLE_BUTTON);
      }
    },
    [sideContentsVisible]
  );

  const onSpotlightUp = useCallback(
    (e) => {
      if (!sideContentsVisible) {
        e.stopPropagation();
        Spotlight.focus("videoIndicator-up-button");
      }
    },
    [sideContentsVisible]
  );

  return (
    <Container
      className={classNames(
        css.arrow,
        sideContentsVisible && css.arrowOpen,
        !sideContentsVisible && css.arrowClose
      )}
    >
      <SpottableComponent
        spotlightId="playerTabArrow"
        onClick={handleTabOnClick}
        onSpotlightLeft={_onSpotlightLeft}
        onSpotlightUp={onSpotlightUp}
        onSpotlightDown={onSpotlightDown}
        className={css.button}
        aria-label="See item list"
      />
    </Container>
  );
}
