import React, { useCallback, useEffect, useRef, useState } from 'react';

import { useDispatch } from 'react-redux';

import Spotlight from '@enact/spotlight';

import { sendLogTotalRecommend } from '../../../../actions/logActions';
// <<<<<<< HEAD
import { updatePanel } from '../../../../actions/panelActions';
import TVirtualGridList from '../../../../components/TVirtualGridList/TVirtualGridList';
import {
  LOG_CONTEXT_NAME,
  LOG_MENU,
  LOG_MESSAGE_ID,
  panel_names,
} from '../../../../utils/Config';
import { $L } from '../../../../utils/helperMethods';
import PlayerItemCard, { TYPES } from '../../PlayerItemCard/PlayerItemCard';
import ListEmptyContents from '../TabContents/ListEmptyContents/ListEmptyContents';
import css from './LiveChannelContents.module.less';
import cssV2 from './LiveChannelContents.v2.module.less';

// =======
// import { updatePanel } from "../../../../actions/panelActions";
// import TVirtualGridList from "../../../../components/TVirtualGridList/TVirtualGridList";
// import {
//   LOG_CONTEXT_NAME,
//   LOG_MENU,
//   LOG_MESSAGE_ID,
//   panel_names,
// } from "../../../../utils/Config";
// import { $L } from "../../../../utils/helperMethods";
// import PlayerItemCard, { TYPES } from "../../PlayerItemCard/PlayerItemCard";
// import ListEmptyContents from "../TabContents/ListEmptyContents/ListEmptyContents";
// import css from "./LiveChannelContents.module.less";
// import { sendLogTotalRecommend } from "../../../../actions/logActions";
// >>>>>>> gitlab/develop

export default function LiveChannelContents({
  liveInfos,
  currentTime,
  setSelectedIndex,
  videoVerticalVisible,
  currentVideoShowId,
  tabIndex,
  handleItemFocus,
  tabTitle,
  panelInfo,
  // <<<<<<< HEAD
  direction = 'vertical',
  version = 1,
  isFilteredByPatnr19,
}) {
  const dispatch = useDispatch();
  const isClickBlocked = useRef(false);
  const blockTimeoutRef = useRef(null);

  // =======
  //   isFilteredByPatnr19,
  // }) {
  //   const dispatch = useDispatch();
  //   const isClickBlocked = useRef(false);
  const scrollToRef = useRef(null);
  // >>>>>>> gitlab/develop
  const handleFocus = useCallback(
    () => () => {
      if (handleItemFocus) {
        handleItemFocus(LOG_MENU.FULL_LIVE_CHANNELS);
      }
    },
    [handleItemFocus]
  );

  // cbScrollTo 콜백으로 scrollTo 함수 받기
  const handleScrollTo = useCallback((scrollToFn) => {
    scrollToRef.current = scrollToFn;
  }, []);

  // VOD Channel로 전환될 때 스크롤을 최상단으로 이동
  useEffect(() => {
    if (isFilteredByPatnr19 && scrollToRef.current) {
      scrollToRef.current({ index: 0, animate: false, focus: false });
    }
  }, [isFilteredByPatnr19]);

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

      const handleItemClick = () => {
        const params = {
          tabTitle: tabTitle[tabIndex],
          showId: showId,
          showTitle: showNm,
          showType: panelInfo?.shptmBanrTpNm,
          category: catNm,
          partner: patncNm,
          contextName: LOG_CONTEXT_NAME.SHOW,
          messageId: LOG_MESSAGE_ID.CONTENTCLICK,
        };
        dispatch(sendLogTotalRecommend(params));
        //중복클릭방지
        if (isClickBlocked.current) {
          return;
        }

        isClickBlocked.current = true;

        // 이전 타이머가 있으면 정리
        if (blockTimeoutRef.current) {
          clearTimeout(blockTimeoutRef.current);
        }

        blockTimeoutRef.current = setTimeout(() => {
          isClickBlocked.current = false;
          blockTimeoutRef.current = null;
        }, 600);

        if (!showId) return;

        if (currentVideoShowId && currentVideoShowId === showId) {
          return;
        }
        setSelectedIndex(index);
        dispatch(
          updatePanel({
            name: panel_names.PLAYER_PANEL,
            panelInfo: {
              chanId,
              patnrId,
              showId,
              shptmBanrTpNm: 'LIVE',
              lgCatCd: catCd,
              isUpdatedByClick: true,
            },
          })
        );
      };

      const showNameDangerouslySetInnerHTML = () => {
        if (!showId) {
          return { __html: $L('No Livestream scheduled yet') };
        }
        return showNm ? { __html: showNm } : { __html: patncNm };
      };

      return (
        <PlayerItemCard
          {...rest}
          key={prdtId}
          imageAlt={prdtId}
          logo={patncLogoPath}
          imageSource={thumbnailUrl ? thumbnailUrl : dfltThumbnailImgPath}
          videoVerticalVisible={videoVerticalVisible}
          productName={showNameDangerouslySetInnerHTML}
          patnerName={patncNm}
          onClick={handleItemClick}
          onFocus={handleFocus()}
          onSpotlightUp={
            version === 2 && index === 0
              ? (e) => {
                  // v2에서 첫 번째 아이템일 때 위로 가면 LIVE CHANNEL 버튼으로
                  e.stopPropagation();
                  e.preventDefault();
                  Spotlight.focus('below-tab-live-channel-button');
                }
              : undefined
          }
          type={TYPES.liveHorizontal}
          spotlightId={`tabChannel-video-${index}`}
          liveInfo={liveInfos[index]}
          startDt={strtDt}
          endDt={endDt}
          currentTime={currentTime}
          currentVideoVisible={currentVideoShowId === liveInfos[index].showId}
          // <<<<<<< HEAD
          version={version}
          // =======
          //           currentVideoVisible={currentVideoShowId === liveInfos[index].showId}
          // >>>>>>> gitlab/develop
        />
      );
    },
    [
      liveInfos,
      currentTime,
      currentVideoShowId,
      isClickBlocked,
      dispatch,
      handleFocus,
      version,
    ]
  );

  const containerClass = version === 2 ? cssV2.container : css.container;

  // cleanup useEffect
  useEffect(() => {
    return () => {
      if (blockTimeoutRef.current) {
        clearTimeout(blockTimeoutRef.current);
      }
    };
  }, []);

  return (
    <>
      <div className={containerClass}>
        {liveInfos && liveInfos.length > 0 ? (
          <TVirtualGridList
            cbScrollTo={handleScrollTo}
            dataSize={liveInfos.length}
            direction={direction}
            renderItem={renderItem}
            itemWidth={version === 2 ? 470 : videoVerticalVisible ? 540 : 600}
            itemHeight={version === 2 ? 155 : 236}
            spacing={version === 2 ? 30 : 12}
            noScrollByWheel={false}
          />
        ) : (
          <ListEmptyContents tabIndex={tabIndex} />
        )}
      </div>
    </>
  );
}
