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

function ReservedTimer() {
  const [currentDate, setCurrentDate] = useState(new Date());
  const endDate = useMemo(
    () => new Date().setMinutes(currentDate.getMinutes() + 20),
    // 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.container}>
      <img
        className={styles.background}
        src="/timerBackground.webp"
        alt="Timer background"
      />
      <div className={styles["text-container"]}>
        <span>Reserved for</span>
        <div className={styles.value}>
          {getMinutes()}:{getSeconds()}
        </div>
      </div>
    </div>
  );
}

export default ReservedTimer;
