import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { toLocaleDigits } from '@/utils/persianDigit';

interface CountdownTimerProps {
  initialSeconds: number;
  onComplete?: () => void;
}

export function CountDownTimer({
  initialSeconds,
  onComplete,
}: CountdownTimerProps) {
  const { i18n } = useTranslation();
  const [secondsLeft, setSecondsLeft] = useState(initialSeconds);

  useEffect(() => {
    setSecondsLeft(initialSeconds);

    const timer = setInterval(() => {
      setSecondsLeft((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          onComplete?.();
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [initialSeconds, onComplete]);

  const formatTime = (totalSeconds: number) => {
    const minutes = String(Math.floor(totalSeconds / 60)).padStart(2, '0');
    const seconds = String(totalSeconds % 60).padStart(2, '0');
    return toLocaleDigits(`${minutes}:${seconds}`, i18n.language);
  };

  return <span>{formatTime(secondsLeft)}</span>;
}
