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

import { useDispatch } from "react-redux";

import Spotlight from "@enact/spotlight";

import defaultImage from "../../../../../assets/images/img-thumb-empty-144@3x.png";
import { updatePanel } from "../../../../actions/panelActions";
import TVirtualGridList from "../../../../components/TVirtualGridList/TVirtualGridList";
import { panel_names } from "../../../../utils/Config";
import PlayerItemCard, { TYPES } from "../../PlayerItemCard/PlayerItemCard";
import css from "./LiveChannelContents.module.less";
import PlayerTabLoading from "./PlayerTabLoading";

export default function FeaturedShowContents({
  featuredShowsInfos,
  setSelectedIndex,
}) {
  const dispatch = useDispatch();

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const {
        thumbnailUrl,
        patncLogoPath,
        patnrId,
        showId,
        prdtId,
        patncNm,
        showNm,
      } = featuredShowsInfos[index];

      const handleItemClick = () => {
        setSelectedIndex(index);

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

      return (
        <PlayerItemCard
          {...rest}
          key={prdtId}
          imageAlt={prdtId}
          logo={patncLogoPath}
          imageSource={thumbnailUrl ? thumbnailUrl : defaultImage}
          productName={showNm}
          patnerName={patncNm}
          onClick={handleItemClick}
          type={TYPES.featuredHorizontal}
          spotlightId={`tabChannel-video-${index}`}
        />
      );
    },
    [featuredShowsInfos]
  );

  useEffect(() => {
    const timer = setTimeout(() => {
      Spotlight.focus("featuredShows-video-0");
    });

    return () => clearTimeout(timer);
  }, [featuredShowsInfos]);

  return (
    <>
      <div className={css.container}>
        {featuredShowsInfos && featuredShowsInfos.length > 0 ? (
          <TVirtualGridList
            dataSize={featuredShowsInfos.length}
            direction="vertical"
            renderItem={renderItem}
            itemWidth={600}
            itemHeight={176}
            spacing={12}
            className={css.itemList}
            noScrollByWheel={false}
          />
        ) : (
          <PlayerTabLoading />
        )}
      </div>
    </>
  );
}
