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

import classNames from "classnames";

import Spotlight from "@enact/spotlight";
import Spottable from "@enact/spotlight/Spottable";

import CustomImage from "../../../../components/CustomImage/CustomImage";
import { convertUtcToLocal } from "../../../../components/MediaPlayer/util";
import TCheckBox from "../../../../components/TCheckBox/TCheckBox";
import * as HelperMethods from "../../../../utils/helperMethods";
import { $L } from "../../../../utils/helperMethods";
import css from "./RemindersCard.module.less";

const RemindersItem = Spottable("div");

export const SIZES = {
  itemWidth: 315,
  itemHeight: 177,
  spacing: 26,
};

export default memo(function RemindersCard({
  hstNm,
  patncLogoPath,
  patncNm,
  showId,
  showNm,
  strtDt,
  activeDelete,
  selected,
  onToggle,
  onFocus,
  onBlur,
  index,
  length,
  endDt,
  dfltThumbnailImgPath,
  thumbnailUrl,
}) {
  const [focus, setFocus] = useState(false);

  const _onFocus = useCallback(() => {
    Spotlight.focus("mypage-reminder-checkbox" + index);
    setFocus(true);
    onFocus && onFocus();
  }, [index, onFocus]);

  const _onFocusBox = useCallback(() => {
    Spotlight.focus("mypage-reminder-checkbox" + index);
  }, [index]);

  const _onBlur = useCallback(() => {
    setFocus(false);
    onBlur && onBlur();
  }, [onBlur]);

  const dDay = strtDt.split(" ")[0];
  const dDayTime = strtDt.split(" ")[1];
  const endDay = endDt.split(" ")[0];
  const endTime = endDt.split(" ")[1];
  const [lessDay, setlessDay] = useState("");
  const [lessTime, setlessTime] = useState("");
  const [dayOver, setDayOver] = useState(false);
  const [isEndTime, setIsEndTime] = useState(false);
  const [liveTime, setLiveTime] = useState(false);
  const [progressPercent, setProgressPercent] = useState();

  const hostText = hstNm !== null && hstNm !== "" ? hstNm : "";
  const ariaLabel =
    HelperMethods.convertToTimeFormat(convertUtcToLocal(strtDt), true) +
    `, "` +
    showNm +
    `", ` +
    hostText +
    `", ` +
    patncNm;

  const partnerName = patncNm && patncNm.toUpperCase();

  // 디데이 설정 후 남은 시간 계산
  useEffect(() => {
    const calculateTimeLeft = () => {
      const today = new Date();
      const dDayDate = convertUtcToLocal(`${dDay} ${dDayTime}`);
      const endDayDate = convertUtcToLocal(`${endDay} ${endTime}`);
      if (!dDayDate || !endDayDate) return;

      const differenceInTime = dDayDate.getTime() - today.getTime();
      const days = Math.floor(differenceInTime / (1000 * 60 * 60 * 24));
      const diffEndTime = endDayDate.getTime() - today.getTime();
      const elapsed = today.getTime() - dDayDate.getTime();
      const duration = endDayDate.getTime() - dDayDate.getTime();
      const percent = (elapsed / duration) * 100;

      setProgressPercent(percent);

      // 시간
      const hours = Math.floor(
        (differenceInTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
      )
        .toString()
        .padStart(2, "0");

      // 분
      const minutes = Math.floor(
        (differenceInTime % (1000 * 60 * 60)) / (1000 * 60)
      )
        .toString()
        .padStart(2, "0");

      // 초
      const seconds = Math.floor((differenceInTime % (1000 * 60)) / 1000)
        .toString()
        .padStart(2, "0");

      if (differenceInTime < 0) {
        setDayOver(true);
      }

      if (diffEndTime <= 0) {
        setIsEndTime(true);
      }

      if (dDayDate <= today && today <= endDayDate) {
        setLiveTime(true);
      }

      setlessDay(days);
      setlessTime(`${hours}:${minutes}:${seconds}`);
    };

    if (dDay && dDayTime) {
      calculateTimeLeft();
    }
  }, [focus]);

  return (
    <div
      className={classNames(
        css.container,
        patncNm && css[partnerName],
        liveTime && css.liveTimeContainer
      )}
    >
      <RemindersItem
        className={css.itemContainer}
        onFocus={() => {
          activeDelete === false ? _onFocus(index) : _onFocusBox(index);
        }}
        onBlur={_onBlur}
        index={index}
        spotlightDisabled={activeDelete}
        aria-label={ariaLabel}
      >
        {!liveTime ? (
          <>
            <p className={css.strtDt}>
              {HelperMethods.convertToTimeFormat(
                convertUtcToLocal(strtDt),
                true
              )}
            </p>
            <h2 className={css.showNm}>{showNm}</h2>

            {hstNm !== null && hstNm !== "" && (
              <span className={css.hstNm}>With Host {hstNm}</span>
            )}

            <CustomImage
              src={patncLogoPath}
              delay={0}
              alt={showId}
              className={css.patncLogo}
            />
          </>
        ) : (
          <div className={css.live}>
            <CustomImage
              src={
                thumbnailUrl.length > 1 ? thumbnailUrl : dfltThumbnailImgPath
              }
              delay={0}
              alt={showId}
              className={css.thumbnail}
            />
            <div className={css.liveBox}>LIVE</div>
            <div className={css.progressBarContainer}>
              <div
                className={css.progressBar}
                style={{ width: `${progressPercent}%` }}
              />
            </div>
          </div>
        )}
        {!liveTime && !isEndTime && focus && activeDelete === false && (
          <div className={css.timeOvelay}>
            <div>
              <p>{$L("Coming Soon")}</p>
              <p>{lessDay > 0 ? lessDay + " " + $L("Days") : lessTime}</p>
            </div>
          </div>
        )}
      </RemindersItem>

      {activeDelete && (
        <div
          className={classNames(css.checkboxOverlay, focus && css.focus)}
          onFocus={_onFocus}
          onBlur={_onBlur}
        >
          <TCheckBox
            className={classNames(
              css.checkbox,
              focus && css.focus,
              focus && selected && css.selectedFocus
            )}
            selected={selected}
            onToggle={onToggle}
            spotlightId={"mypage-reminder-checkbox" + index}
          />
        </div>
      )}
    </div>
  );
});
