import { ef } from '@/lib/helpers/utfNumbers';
import type { TFunction } from 'i18next';
import { useEffect, useRef, useState } from 'react';

export const formatCountdown = (seconds: number, t: TFunction) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;

  if (mins > 0 && secs > 0) {
    return ef(t('OTP.Countdown.MinuteAndSecond', { mins, secs }));
  }
  if (mins > 0) {
    return ef(t('OTP.Countdown.Minute', { count: mins }));
  }
  return ef(t('OTP.Countdown.Second', { count: secs }));
};

export const useCountdown = (shouldStart: boolean, duration: number = 30, delay: number = 1000) => {
  const [timerRunning, setTimerRunning] = useState(false);
  const [secondsLeft, setSecondsLeft] = useState(duration);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (shouldStart) {
      setSecondsLeft(duration);
      setTimerRunning(true);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shouldStart]);

  const stop = () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
  }

  const restart = () => {
    stop();
    setSecondsLeft(duration);
    setTimerRunning(true);
  }

  useEffect(() => {
    if (timerRunning && intervalRef.current === null) {
      intervalRef.current = setInterval(() => {
        setSecondsLeft((prev) => {
          if (prev <= 1) {
            setTimerRunning(false);
            clearInterval(intervalRef.current!);
            intervalRef.current = null;
            return 0;
          }
          return prev - 1;
        });
      }, delay);
    }

    return () => {
      stop();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [timerRunning]);

  return { timerRunning, secondsLeft, setTimerRunning, setSecondsLeft, stop, restart };
};
