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

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

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

import { setShowPopup } from "../../../../actions/commonActions";
import { sendLogUpcomingFlag } from "../../../../actions/logActions";
import { setMainLiveUpcomingAlarm } from "../../../../actions/mainActions";
import { getMyUpcomingAlertShow } from "../../../../actions/myPageActions";
// import { convertUtcToLocal } from "../../../../components/MediaPlayer/util";
import TVirtualGridList from "../../../../components/TVirtualGridList/TVirtualGridList";
import useScrollTo from "../../../../hooks/useScrollTo";
import {
  ACTIVE_POPUP,
  LOG_CONTEXT_NAME,
  LOG_MESSAGE_ID,
} from "../../../../utils/Config";
// import { formatGMTString } from "../../../../utils/helperMethods";
import UpComingCard from "./UpComingCard/UpComingCard";
import css from "./UpComingList.module.less";

const getTimeDifferenceInSeconds = (strtDt) => {
  const isoStrtDt = strtDt.replace(" ", "T");
  const currentDt = new Date().toISOString().split(".")[0];

  const startDate = new Date(isoStrtDt);
  const currentDate = new Date(currentDt);

  const timeDifferenceInMillis = startDate - currentDate;

  const timeDifferenceInSeconds = timeDifferenceInMillis / 1000;

  return timeDifferenceInSeconds;
};

export default memo(function UpComingList({
  brandLiveChannelUpcoming,
  handleItemFocus,
  selectedPatnrId,
  shelfTitle,
  shelfId,
  shelfOrder,
}) {
  const { getScrollTo, scrollLeft } = useScrollTo();

  const dispatch = useDispatch();

  const upcomAlamUseFlag = useSelector(
    (state) => state.myPage.upComingData?.upComingAlertShow?.upcomAlamUseFlag
  );

  const alertShows = useSelector(
    (state) => state.myPage.upComingData?.upComingAlertShow?.alertShows
  );

  const alamTimer = useRef(null);

  useEffect(() => {
    const gridListId = "upcoming-list-id";
    const gridList = //
      document.querySelector(`[data-spotlight-id=${gridListId}]`);

    if (gridList) {
      setContainerLastFocusedElement(null, [gridListId]);
    }

    scrollLeft();

    return () => clearTimeout(alamTimer.current);
  }, [scrollLeft, selectedPatnrId]);

  const handleClick = useCallback(
    ({
        chanId,
        endDt,
        hstNm,
        lgCatCd,
        lgCatNm,
        patncNm,
        patnrId,
        showId,
        showNm,
        strtDt,
      }) =>
      () => {
        const selectedAlertShow = alertShows //
          .find((show) => show.showId === showId && show.strtDt === strtDt);

        const deletedAlertShow = alertShows //
          .find((show) => show.showId !== showId && show.strtDt === strtDt);

        const isTimeConflict = alertShows //
          .some((show) => show.showId !== showId && show.strtDt === strtDt);

        const alamDispFlag = selectedAlertShow?.alamDispFlag;
        // const isShowStarted = formatGMTString(new Date()) >= strtDt;
        const isReminderOff = upcomAlamUseFlag === "N";
        const isReserved = alamDispFlag === "Y";

        const upcomingAlarmInfo = {
          alamDispFlag: "Y",
          chanId, // for system alert
          endDt,
          patncNm, // for system alert
          patnrId,
          showId,
          showNm, // for system alert
          strtDt,
        };

        if (isReminderOff) {
          return dispatch(setShowPopup({ type: ACTIVE_POPUP.reminderPopup }));
        }
        //
        // else if (isShowStarted) {
        //   return dispatch(setShowPopup({ type: ACTIVE_POPUP.noShowPopup }));
        // }
        //
        else if (isTimeConflict) {
          return dispatch(
            setShowPopup({
              type: ACTIVE_POPUP.timeConflictPopup,
              upcomingAlarmInfo,
              deletedAlertShows: [
                {
                  patnrId: deletedAlertShow?.patnrId,
                  showId: deletedAlertShow?.showId,
                },
              ],
            })
          );
        }
        //
        else {
          dispatch(
            setMainLiveUpcomingAlarm({
              ...upcomingAlarmInfo,
              alamDispFlag: isReserved ? "N" : "Y",
            })
          );

          dispatch(
            sendLogUpcomingFlag({
              items: [
                {
                  alertFlag: isReserved ? "Off" : "On",
                  hstNm: hstNm ?? "",
                  lgCatCd: lgCatCd ?? "",
                  lgCatNm: lgCatNm ?? "",
                  patncNm,
                  patnrId,
                  remainSec: getTimeDifferenceInSeconds(strtDt).toString(),
                  showId,
                  showNm,
                },
              ],
            })
          );

          alamTimer.current = setTimeout(
            () => dispatch(getMyUpcomingAlertShow()),
            200
          );
        }
      },
    [alertShows, dispatch, upcomAlamUseFlag]
  );

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

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const { hstNm, showId, showNm, strtDt, patncNm, lgCatNm, brndNm } =
        brandLiveChannelUpcoming[index];

      const selectedAlertShow = Array.isArray(alertShows)
        ? alertShows.find(
            (show) => show?.showId === showId && show?.strtDt === strtDt
          )
        : null;
      const alamDispFlag = selectedAlertShow?.alamDispFlag;

      return (
        <UpComingCard
          alamDispFlag={alamDispFlag}
          hstNm={hstNm}
          showNm={showNm}
          strtDt={strtDt}
          onClick={handleClick(brandLiveChannelUpcoming[index])}
          onFocus={handleFocus}
          contextName={LOG_CONTEXT_NAME.FEATURED_BRANDS}
          messageId={LOG_MESSAGE_ID.SHELF_CLICK}
          shelfTitle={shelfTitle}
          shelfOrder={shelfOrder}
          shelfId={shelfId}
          partnerName={patncNm}
          order={index + 1}
          showId={showId}
          catNm={lgCatNm}
          brandName={brndNm}
          {...rest}
        />
      );
    },
    [alertShows, brandLiveChannelUpcoming, handleClick, handleFocus]
  );

  return (
    <div className={css.container}>
      {brandLiveChannelUpcoming && (
        <TVirtualGridList
          cbScrollTo={getScrollTo}
          className={css.tVirtualGridList}
          dataSize={brandLiveChannelUpcoming.length}
          direction="horizontal"
          itemHeight={344}
          itemWidth={480}
          spacing={18}
          spotlightId="upcoming-list-id"
          renderItem={renderItem}
        />
      )}
    </div>
  );
});
