import { useEffect } from "react";
import styles from "./styles.module.scss";
import { sleep } from "@/services/date";

interface ITimerProps {
  seconds: number;
  onChangeSeconds: (seconds: number) => void;
}

function Timer({ seconds, onChangeSeconds }: ITimerProps) {
  useEffect(() => {
    (async () => {
      await sleep(1000);
      if (seconds > 0) {
        onChangeSeconds(seconds - 1);
      }
    })();
  }, [onChangeSeconds, seconds]);

  const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, "0")} : ${remainingSeconds
      .toString()
      .padStart(2, "0")}`;
  };

  return <div className={styles.container}>{formatTime(seconds)}</div>;
}

export default Timer;
