import { ref, onMounted, onUnmounted, Ref } from 'vue';

export const useCountdownTimer = (
  initialSeconds: number,
  refreshCallback: () => void
): { seconds: Ref<number> } => {
  const seconds: Ref<number> = ref(initialSeconds);
  let timerId: number;

  const startTimer = (): void => {
    timerId = setInterval(() => {
      seconds.value--;

      if (seconds.value === 0) {
        clearInterval(timerId);
        refreshCallback();
        restartTimer();
      }
    }, 1000);
  };

  const stopTimer = (): void => {
    clearInterval(timerId);
  };

  const restartTimer = (): void => {
    seconds.value = initialSeconds;
    startTimer();
  };

  onMounted(() => {
    startTimer();
  });

  onUnmounted(() => {
    stopTimer();
  });

  return {
    seconds
  };
};
