import { useEffect, useRef, useState } from 'react';
import { ProgressRing } from '@/components/ui/ProgressRing';
import { cn } from '@/lib/cn';

interface CountdownTimerProps {
  deadline: string;
  onExpire?: () => void;
}

export function CountdownTimer({ deadline, onExpire }: CountdownTimerProps) {
  const [remaining, setRemaining] = useState(0);
  const expiredRef = useRef(false);
  const total = 180;

  useEffect(() => {
    expiredRef.current = false;
    const update = () => {
      const diff = Math.max(0, Math.floor((new Date(deadline).getTime() - Date.now()) / 1000));
      setRemaining(diff);
      if (diff === 0 && onExpire && !expiredRef.current) {
        expiredRef.current = true;
        onExpire();
      }
    };
    update();
    const interval = setInterval(update, 1000);
    return () => clearInterval(interval);
  }, [deadline, onExpire]);

  const minutes = Math.floor(remaining / 60);
  const seconds = remaining % 60;
  const color = remaining < 30 ? '#EF4444' : remaining < 60 ? '#F59E0B' : '#22C55E';
  const percentage = (remaining / total) * 100;

  return (
    <ProgressRing
      value={percentage}
      size={140}
      strokeWidth={6}
      color={color}
    >
      <div className="text-center">
        <span className={cn(
          'text-3xl font-mono font-bold',
          remaining < 30 ? 'text-red-400' : remaining < 60 ? 'text-amber-400' : 'text-text-primary'
        )}>
          {minutes}:{seconds.toString().padStart(2, '0')}
        </span>
        <p className="text-xs text-text-muted mt-0.5">to join</p>
      </div>
    </ProgressRing>
  );
}
