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

import { useDispatch } from "react-redux";

import Spotlight from "@enact/spotlight";

import { updatePanel } from "../../../../actions/panelActions";
import TVirtualGridList from "../../../../components/TVirtualGridList/TVirtualGridList";
import { LOG_MENU, panel_names } from "../../../../utils/Config";
import { $L } from "../../../../utils/helperMethods";
import ListEmptyContents from "../../../ImagePanel/ImageSideContents/ListEmptyContents/ListEmptyContents";
import PlayerItemCard, { TYPES } from "../../PlayerItemCard/PlayerItemCard";
import css from "./LiveChannelContents.module.less";

export default function LiveChannelContents({
  liveInfos,
  selectedIndex,
  setSelectedIndex,
  videoVerticalVisible,
  tabIndex,
  handleItemFocus,
}) {
  const dispatch = useDispatch();

  const handleFocus = useCallback(
    () => () => {
      if (handleItemFocus) {
        handleItemFocus(LOG_MENU.FULL_LIVE_CHANNELS);
      }
    },
    [handleItemFocus]
  );

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const {
        dfltThumbnailImgPath,
        patncLogoPath,
        prdtId,
        patnrId,
        showId,
        showNm,
        patncNm,
        strtDt,
        endDt,
        timezone,
        thumbnailUrl,
      } = liveInfos[index];

      const handleItemClick = () => {
        if (!showId) return;

        setSelectedIndex(index);
        dispatch(
          updatePanel({
            name: panel_names.PLAYER_PANEL,
            panelInfo: { patnrId, showId, shptmBanrTpNm: "LIVE" },
          })
        );
      };

      return (
        <PlayerItemCard
          {...rest}
          key={prdtId}
          imageAlt={prdtId}
          logo={patncLogoPath}
          imageSource={thumbnailUrl ? thumbnailUrl : dfltThumbnailImgPath}
          videoVerticalVisible={videoVerticalVisible}
          productName={showNm ? showNm : $L("No Livestream scheduled yet")}
          patnerName={patncNm}
          onClick={handleItemClick}
          onFocus={handleFocus()}
          type={TYPES.liveHorizontal}
          spotlightId={`tabChannel-video-${index}`}
          liveInfo={liveInfos[index]}
        />
      );
    },
    [liveInfos, dispatch, handleFocus]
  );

  return (
    <>
      <div className={css.container}>
        {liveInfos && liveInfos.length > 0 ? (
          <TVirtualGridList
            dataSize={liveInfos.length}
            direction="vertical"
            renderItem={renderItem}
            itemWidth={videoVerticalVisible ? 540 : 600}
            itemHeight={236}
            spacing={12}
            noScrollByWheel={false}
          />
        ) : (
          <ListEmptyContents tabIndex={tabIndex} />
        )}
      </div>
    </>
  );
}
