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

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

import Spotlight from "@enact/spotlight";

import IcUpcomingsNormal from "../../../../../../assets/images/badge/ic-upcomings-nor@3x.png";
import IcUpcomingsReserved from "../../../../../../assets/images/badge/ic-upcomings-sel@3x.png";
import { setShowPopup } from "../../../../../actions/commonActions";
import { sendLogUpcomingFlag } from "../../../../../actions/logActions";
import { setMainLiveUpcomingAlarm } from "../../../../../actions/mainActions";
import { getMyUpcomingAlertShow } from "../../../../../actions/myPageActions";
import { updatePanel } from "../../../../../actions/panelActions";
import { startVideoPlayer } from "../../../../../actions/playActions";
import { convertUtcToLocal } from "../../../../../components/MediaPlayer/util";
import TButton from "../../../../../components/TButton/TButton";
import { ACTIVE_POPUP, panel_names } from "../../../../../utils/Config";
import { $L, convertToTimeFormat } from "../../../../../utils/helperMethods";
import css from "./NoLiveCard.module.less";

const STRING_CONF = {
  RECENTLY_AIRED: "Recently Aired",
  REMOVE_REMINDER: "Remove Reminder",
  SET_REMINDER: "Set a Reminder",
  WITH_HOST: "With Host",
};

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 NoLiveCard({
  brandChanInfoItem,
  handleItemFocus,
}) {
  const dispatch = useDispatch();

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

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

  const brandRecentlyAired = useSelector(
    (state) => state.brand.brandRecentlyAiredData.data.brandRecentlyAired
  );

  const alamTimer = useRef();

  const {
    // alamDispFlag,
    brandProductInfo,
    chanId,
    chanNm,
    endDt,
    hstNm,
    lgCatCd,
    lgCatNm,
    patnrId,
    showId,
    showNm,
    strtDt,
    thumbnailImgPath,
  } = brandChanInfoItem;

  const selectedAlertShow = useMemo(() => {
    if (alertShows) {
      return alertShows //
        .find((show) => show.showId === showId && show.strtDt === strtDt);
    }

    return {};
  }, [alertShows, showId, strtDt]);

  const deletedAlertShow = useMemo(() => {
    if (alertShows) {
      return alertShows //
        .find((show) => show.showId !== showId && show.strtDt === strtDt);
    }

    return {};
  }, [alertShows, showId, strtDt]);

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

  const alamDispFlag = selectedAlertShow?.alamDispFlag;
  const isReminderOff = upcomAlamUseFlag === "N";
  const isReserved = alamDispFlag === "Y";

  useEffect(() => {
    return () => clearTimeout(alamTimer.current);
  }, []);

  const handleReminderClick = useCallback(() => {
    const upcomingAlarmInfo = {
      alamDispFlag: "Y",
      chanId, // for system alert
      endDt,
      patncNm: chanNm, // for system alert
      patnrId,
      showId,
      showNm, // for system alert
      strtDt,
    };

    if (isReminderOff) {
      return dispatch(setShowPopup({ type: ACTIVE_POPUP.reminderPopup }));
    }
    //
    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: chanNm,
              patnrId,
              remainSec: getTimeDifferenceInSeconds(strtDt).toString(),
              showId,
              showNm,
            },
          ],
        })
      );

      alamTimer.current = setTimeout(
        () => dispatch(getMyUpcomingAlertShow()),
        200
      );
    }
  }, [
    chanId,
    chanNm,
    deletedAlertShow?.patnrId,
    deletedAlertShow?.showId,
    dispatch,
    endDt,
    hstNm,
    isReminderOff,
    isReserved,
    isTimeConflict,
    lgCatCd,
    lgCatNm,
    patnrId,
    showId,
    showNm,
    strtDt,
  ]);

  const handleRecentlyAiredClick = useCallback(() => {
    const lastFocusedTarget = Spotlight.getCurrent();
    const lastFocusedTargetId =
      lastFocusedTarget?.getAttribute("data-spotlight-id");

    if (lastFocusedTargetId) {
      const section = "live-channels-vertical";
      const x = 0;

      dispatch(
        updatePanel({
          name: panel_names.FEATURED_BRANDS_PANEL,
          panelInfo: {
            lastFocusedTargetId,
            patnrId: `${brandRecentlyAired?.patnrId}`,
            section,
            x,
          },
        })
      );
    }

    dispatch(
      startVideoPlayer({
        modal: false,
        patnrId: `${brandRecentlyAired?.patnrId}`,
        showId: brandRecentlyAired?.showId,
        shptmBanrTpNm: "VOD",
      })
    );
  }, [brandRecentlyAired?.patnrId, brandRecentlyAired?.showId, dispatch]);

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

  return (
    <div
      className={classNames(
        css.card,
        brandProductInfo && brandProductInfo.length > 0
          ? css.withProductList
          : css.noProductList
      )}
    >
      <figure>
        <img src={thumbnailImgPath} alt={showNm} />
      </figure>

      <div>
        <img
          src={isReserved ? IcUpcomingsReserved : IcUpcomingsNormal}
          alt=""
        />
        <time>{convertToTimeFormat(convertUtcToLocal(strtDt), true)}</time>
        <div className={css.sectionSubTitle}>{showNm}</div>
        <p>{hstNm ? $L(STRING_CONF.WITH_HOST) + " " + hstNm : ""}</p>
        <div>
          <TButton
            className={css.tButton}
            onClick={handleReminderClick}
            onFocus={handleFocus}
            size={null}
          >
            {isReserved
              ? $L(STRING_CONF.REMOVE_REMINDER)
              : $L(STRING_CONF.SET_REMINDER)}
          </TButton>
          {brandRecentlyAired && Object.keys(brandRecentlyAired).length > 0 && (
            <TButton
              className={css.tButton}
              onClick={handleRecentlyAiredClick}
              onFocus={handleFocus}
              size={null}
              spotlightId="spotlightId-recentlyAired"
            >
              {$L(STRING_CONF.RECENTLY_AIRED)}
            </TButton>
          )}
        </div>
      </div>
    </div>
  );
});
