import React, { memo, useEffect } from "react";

import { useDispatch } from "react-redux";

import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import {
  getContainerId,
  setContainerLastFocusedElement,
} from "@enact/spotlight/src/container";

import { getBrandRecentlyAired } from "../../../../actions/brandActions";
import LiveChannelsVerticalProductList from "../LiveChannelsVerticalContents/LiveChannelsVerticalProductList/LiveChannelsVerticalProductList";
import NoLiveCard from "./NoLiveCard/NoLiveCard";
import css from "./NoLiveContents.module.less";

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

export default memo(function NoLiveContents({
  brandChanInfoItem,
  contentsIndex,
  handleItemFocus,
  selectedPatnrId,
}) {
  const dispatch = useDispatch();

  const { brandProductInfo, patnrId } = brandChanInfoItem;

  useEffect(() => {
    dispatch(getBrandRecentlyAired({ patnrId: selectedPatnrId }));
  }, [dispatch, selectedPatnrId]);

  useEffect(() => {
    if (brandProductInfo && brandProductInfo.length > 0) {
      const containerId = "no-live-contents-id-" + contentsIndex;
      const container = document.getElementById(containerId);

      if (container) {
        const gridListId = getContainerId(
          container.children[1]?.children[0].children[0]
        );
        const gridList = container.children[1]?.children[0].children[0];
        if (gridListId && gridList) {
          setContainerLastFocusedElement(null, [gridListId]);
        }
      }
    }
  }, [brandProductInfo, contentsIndex, selectedPatnrId]);

  return (
    <Container
      className={css.container}
      id={"no-live-contents-id-" + contentsIndex}
    >
      <NoLiveCard
        brandChanInfoItem={brandChanInfoItem}
        handleItemFocus={handleItemFocus}
      />
      {brandProductInfo && brandProductInfo.length > 0 && (
        <LiveChannelsVerticalProductList
          brandProductInfo={brandProductInfo}
          handleItemFocus={handleItemFocus}
          patnrId={patnrId}
          selectedPatnrId={selectedPatnrId}
        />
      )}
    </Container>
  );
});
