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

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

import Spotlight from "@enact/spotlight";
import { SpotlightContainerDecorator } from "@enact/spotlight/SpotlightContainerDecorator";

import { getBrandChanInfo } from "../../../actions/brandActions";
import { changeBroadcastEvent } from "../../../actions/commonActions";
import { getMyUpcomingAlertShow } from "../../../actions/myPageActions";
import { finishVideoPreview } from "../../../actions/playActions";
import SectionTitle from "../../../components/SectionTitle/SectionTitle";
import { $L } from "../../../utils/helperMethods";
import css from "./LiveChannels.module.less";
import LiveChannelsErrorContents from "./LiveChannelsErrorContents/LiveChannelsErrorContents";
import LiveChannelsHorizontalContents from "./LiveChannelsHorizontalContents/LiveChannelsHorizontalContents";
import LiveChannelsVerticalContents from "./LiveChannelsVerticalContents/LiveChannelsVerticalContents";
import NoLiveContents from "./NoLiveContents/NoLiveContents";

const STRING_CONF = {
  LIVE_CHANNELS: "LIVE CHANNELS",
};

const Container = SpotlightContainerDecorator({ enterTo: null }, "div");

const LiveChannels = ({
  brandChanInfo,
  brandChannelCnt,
  handleItemFocus,
  isOnTop,
  order,
  shelfOrder,
  shelfTitle,
  selectedPatnrId,
  spotlightId,
}) => {
  const dispatch = useDispatch();

  const broadcast = useSelector((state) => state.common.broadcast);
  const panelInfo = useSelector((state) => state.panels.panels[0]?.panelInfo);

  const [isVideoErrorOccurred, setIsVideoErrorOccurred] = useState(false);
  const [firstChk, setFirstChk] = useState(0);

  const intervalRef = useRef(null);

  useEffect(() => dispatch(getMyUpcomingAlertShow()), []);

  useEffect(() => {
    dispatch(changeBroadcastEvent({}));
    setIsVideoErrorOccurred(false);
  }, [panelInfo?.patnrId]);

  useEffect(() => {
    if (Object.keys(broadcast).length === 0) setIsVideoErrorOccurred(false);
    else {
      if (broadcast?.type === "videoError" && !isVideoErrorOccurred) {
        dispatch(finishVideoPreview());
        setIsVideoErrorOccurred(true);
        setTimeout(() =>
          Spotlight.focus(document.querySelector(`[data-wheel-point]`))
        );
      }
    }
  }, [broadcast, isVideoErrorOccurred]);

  useEffect(() => {
    if (brandChannelCnt === 0 || isVideoErrorOccurred) {
      return clearInterval(intervalRef.current);
    }

    intervalRef.current = setInterval(() => {
      dispatch(
        getBrandChanInfo({ patnrId: selectedPatnrId ?? panelInfo?.patnrId })
      );
    }, 30000);

    return () => clearInterval(intervalRef.current);
  }, [
    brandChannelCnt,
    isVideoErrorOccurred,
    panelInfo?.patnrId,
    selectedPatnrId,
  ]);

  const liveChannelsTitle = useMemo(() => {
    if (brandChanInfo[0]?.patncNm === "Pinkfong") {
      return "Subscription";
    }

    return $L(STRING_CONF.LIVE_CHANNELS);
  }, [brandChanInfo]);

  const _handleItemFocus = useCallback(() => {
    if (handleItemFocus) handleItemFocus(spotlightId, shelfOrder);

    const c = Spotlight.getCurrent();

    if (firstChk === 0) {
      if (c) {
        let cAriaLabel = c.getAttribute("aria-label");
        cAriaLabel = "LIVE CHANNELS, Heading1," + cAriaLabel;
        c.setAttribute("aria-label", cAriaLabel);
      }
      setFirstChk(1);
    } else if (firstChk === 1) {
      if (c) {
        let cAriaLabel = c.getAttribute("aria-label");
        if (cAriaLabel) {
          const newcAriaLabel = cAriaLabel.replace(
            "LIVE CHANNELS, Heading1,",
            ""
          );
          c.setAttribute("aria-label", newcAriaLabel);
        }
      }
    } else {
      return;
    }
  }, [handleItemFocus, firstChk]);

  return (
    <Container
      className={css.container}
      data-shelf-order={order}
      data-wheel-point
      spotlightId={spotlightId}
    >
      {brandChanInfo && brandChanInfo.length > 0 && (
        <SectionTitle
          title={liveChannelsTitle}
          data-title="live-channels"
          aria-label="LIVE CHANNELS, Heading1"
        />
      )}

      {broadcast?.type === "videoError" && isVideoErrorOccurred ? (
        <LiveChannelsErrorContents />
      ) : (
        <>
          {brandChannelCnt === 0 && (
            <>
              {brandChanInfo
                .slice(0, 1)
                .map(
                  (brandChanInfoItem, contentsIndex) =>
                    brandChanInfoItem.liveYn === "Y" && (
                      <NoLiveContents
                        brandChanInfoItem={brandChanInfoItem}
                        contentsIndex={contentsIndex}
                        handleItemFocus={_handleItemFocus}
                        key={`${spotlightId}-${contentsIndex}`}
                        selectedPatnrId={selectedPatnrId}
                      />
                    )
                )}
            </>
          )}

          {Number(brandChannelCnt) === 1 && (
            <>
              {brandChanInfo
                .slice(0, 1)
                .map(
                  (brandChanInfoItem, contentsIndex) =>
                    (brandChanInfoItem.liveYn === "Y" ||
                      brandChanInfoItem.patncNm === "Pinkfong") && (
                      <LiveChannelsVerticalContents
                        brandChanInfoItem={brandChanInfoItem}
                        contentsIndex={contentsIndex}
                        handleItemFocus={_handleItemFocus}
                        isOnTop={isOnTop}
                        key={`${spotlightId}-${contentsIndex}`}
                        selectedPatnrId={selectedPatnrId}
                        spotlightId={spotlightId}
                        shelfTitle={shelfTitle}
                        shelfOrder={shelfOrder}
                      />
                    )
                )}
            </>
          )}

          {brandChannelCnt > 1 && (
            <>
              {brandChanInfo.map(
                (brandChanInfoItem, contentsIndex) =>
                  brandChanInfoItem.liveYn === "Y" && (
                    <LiveChannelsHorizontalContents
                      brandChanInfoItem={brandChanInfoItem}
                      contentsIndex={contentsIndex}
                      handleItemFocus={_handleItemFocus}
                      key={`${spotlightId}-${contentsIndex}`}
                      selectedPatnrId={selectedPatnrId}
                      spotlightId={spotlightId}
                      shelfTitle={shelfTitle}
                      shelfOrder={shelfOrder}
                    />
                  )
              )}
            </>
          )}
        </>
      )}
    </Container>
  );
};

export default memo(LiveChannels);
