"use client";
import { ConvertHHMMSST, convertHHMMSS } from "@/lib/utils";
import { useEffect, useState } from "react";

type UseCountDownT = {
  timer: ConvertHHMMSST;
  startCountdown: () => void;
  completed: boolean;
  setCountDownValue: (val: number) => void;
  tracker: boolean;
};

let id: NodeJS.Timeout;

const useCountDown = (number: number = 0): UseCountDownT => {
  let num = number;
  let time = convertHHMMSS(number);
  const [intervalId, setIntervalId] = useState<NodeJS.Timeout>();
  const [timer, setTimer] = useState(time);
  const [completed, setCompleted] = useState(false);
  const [tracker, setTracker] = useState(false);

  function setCountDownValue(value: number) {
    if (value === 0) return;
    num = value;
    setCompleted(false);
    time = convertHHMMSS(value);
    setTracker(true);
    setTimer(time);
  }

  function startCountdown() {
    id = setInterval(() => {
      setIntervalId(id);

      num = num - 1;
      let newTime = convertHHMMSS(num);

      setTimer(() => newTime);

      if (Number(newTime.hours) <= 0) {
        if (Number(newTime.minutes) <= 0) {
          if (Number(newTime.seconds) <= 0) {
            setCompleted(true);
            setTracker(false);
            clearInterval(id);
          }
        }
      }
    }, 1000);
  }

  useEffect(() => {
    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, []);

  return {
    timer,
    startCountdown,
    completed,
    setCountDownValue,
    tracker,
  };
};

export default useCountDown;
