import { useEffect, useState } from 'react';
import { Loader2 } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';

interface RetryStatus {
  attempt: number;
  maxAttempts: number;
  delay: number;
  type: string;
}

/**
 * Global retry status indicator
 * Shows visual feedback when submissions are being retried due to transient failures
 */
export function RetryStatusIndicator() {
  const [retryStatus, setRetryStatus] = useState<RetryStatus | null>(null);
  const [countdown, setCountdown] = useState(0);

  useEffect(() => {
    const handleRetry = (event: Event) => {
      const customEvent = event as CustomEvent<RetryStatus>;
      const { attempt, maxAttempts, delay, type } = customEvent.detail;
      setRetryStatus({ attempt, maxAttempts, delay, type });
      setCountdown(delay);
    };

    window.addEventListener('submission-retry', handleRetry);
    return () => window.removeEventListener('submission-retry', handleRetry);
  }, []);

  useEffect(() => {
    if (countdown > 0) {
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 100) {
            setRetryStatus(null);
            return 0;
          }
          return prev - 100;
        });
      }, 100);
      return () => clearInterval(timer);
    }
  }, [countdown]);

  if (!retryStatus) return null;

  const progress = ((retryStatus.delay - countdown) / retryStatus.delay) * 100;

  return (
    <Card className="fixed bottom-4 right-4 z-50 p-4 shadow-lg border-amber-500 bg-amber-50 dark:bg-amber-950 w-80 animate-in slide-in-from-bottom-4">
      <div className="flex items-start gap-3">
        <Loader2 className="w-5 h-5 animate-spin text-amber-600 dark:text-amber-400 mt-0.5 flex-shrink-0" />
        <div className="flex-1 space-y-2">
          <div className="flex items-center justify-between">
            <p className="text-sm font-medium text-amber-900 dark:text-amber-100">
              Retrying submission...
            </p>
            <span className="text-xs font-mono text-amber-700 dark:text-amber-300">
              {retryStatus.attempt}/{retryStatus.maxAttempts}
            </span>
          </div>
          
          <p className="text-xs text-amber-700 dark:text-amber-300">
            Network issue detected. Retrying {retryStatus.type} submission in {Math.ceil(countdown / 1000)}s
          </p>
          
          <Progress value={progress} className="h-1" />
        </div>
      </div>
    </Card>
  );
}
