import { HTMLAttributes, useEffect, useMemo, useState } from "react";
import styles from "./styles.module.css";
import Title from "@/components/Title";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";

type TDiscountExpiresProps = HTMLAttributes<HTMLDivElement>;

function DiscountExpires({ className = "", ...props }: TDiscountExpiresProps) {
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const [currentDate, setCurrentDate] = useState(new Date());
  const endDate = useMemo(
    () => new Date().setMinutes(currentDate.getMinutes() + 10),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  );

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentDate(new Date());
    }, 1000);
    return () => clearInterval(interval);
  }, [endDate, currentDate]);

  const getMinutes = () => {
    const diff = endDate - currentDate.getTime();
    let minutes = Math.floor(diff / 1000 / 60);
    if (minutes < 0) {
      minutes = 0;
    }
    return minutes.toString().padStart(2, "0");
  };

  const getSeconds = () => {
    const diff = endDate - currentDate.getTime();
    let seconds = Math.floor(diff / 1000) % 60;
    if (seconds < 0) {
      seconds = 0;
    }
    return seconds.toString().padStart(2, "0");
  };

  return (
    <div {...props} className={`${styles["discount-expires"]} ${className}`}>
      <Title variant="h6" className={styles.title}>
        {translate("/trial-payment.discount_expires")}
      </Title>
      <div className={styles.values}>
        <div className={styles["value-container"]}>
          <span className={styles.value}>{getMinutes()}</span>
          <span className={styles["value-symbol"]}>{translate("min")}</span>
        </div>
        <p className={styles.colon}>:</p>
        <div className={styles["value-container"]}>
          <span className={styles.value}>{getSeconds()}</span>
          <span className={styles["value-symbol"]}>{translate("sec")}</span>
        </div>
      </div>
    </div>
  );
}

export default DiscountExpires;
