import { useEffect, useMemo, useState } from "react";
import styles from "./styles.module.css";
import Title from "@/components/Title";

function DiscountExpires() {
  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 className={styles["discount-expires"]}>
      <Title variant="h6" className={styles.title}>
        Discount expires
      </Title>
      <div className={styles.values}>
        <div className={styles["value-container"]}>
          <span className={styles.value}>{getMinutes()}</span>
          <span className={styles["value-symbol"]}>min</span>
        </div>
        <p className={styles.colon}>:</p>
        <div className={styles["value-container"]}>
          <span className={styles.value}>{getSeconds()}</span>
          <span className={styles["value-symbol"]}>sec</span>
        </div>
      </div>
    </div>
  );
}

export default DiscountExpires;
