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

interface RetryStatus {
  id: string;
  attempt: number;
  maxAttempts: number;
  delay: number;
  type: string;
  state: 'retrying' | 'success' | 'failed';
  errorId?: string;
}

/**
 * Global retry status indicator
 * Shows visual feedback when submissions are being retried due to transient failures
 * Supports success/failure states and multiple concurrent retries
 */
export function RetryStatusIndicator() {
  const [retries, setRetries] = useState<Map<string, RetryStatus & { countdown: number }>>(new Map());

  useEffect(() => {
    const handleRetry = (event: Event) => {
      const customEvent = event as CustomEvent<Omit<RetryStatus, 'state'>>;
      const { id, attempt, maxAttempts, delay, type } = customEvent.detail;
      
      setRetries(prev => {
        const next = new Map(prev);
        next.set(id, { id, attempt, maxAttempts, delay, type, state: 'retrying', countdown: delay });
        return next;
      });
    };

    const handleSuccess = (event: Event) => {
      const customEvent = event as CustomEvent<{ id: string }>;
      const { id } = customEvent.detail;
      
      setRetries(prev => {
        const retry = prev.get(id);
        if (!retry) return prev;
        
        const next = new Map(prev);
        next.set(id, { ...retry, state: 'success', countdown: 0 });
        return next;
      });
      
      // Remove after 2 seconds
      setTimeout(() => {
        setRetries(prev => {
          const next = new Map(prev);
          next.delete(id);
          return next;
        });
      }, 2000);
    };

    const handleFailure = (event: Event) => {
      const customEvent = event as CustomEvent<{ id: string; errorId: string }>;
      const { id, errorId } = customEvent.detail;
      
      setRetries(prev => {
        const retry = prev.get(id);
        if (!retry) return prev;
        
        const next = new Map(prev);
        next.set(id, { ...retry, state: 'failed', errorId, countdown: 0 });
        return next;
      });
    };

    window.addEventListener('submission-retry', handleRetry);
    window.addEventListener('submission-retry-success', handleSuccess);
    window.addEventListener('submission-retry-failed', handleFailure);
    
    return () => {
      window.removeEventListener('submission-retry', handleRetry);
      window.removeEventListener('submission-retry-success', handleSuccess);
      window.removeEventListener('submission-retry-failed', handleFailure);
    };
  }, []);

  // Countdown timer for retrying state
  useEffect(() => {
    const timer = setInterval(() => {
      setRetries(prev => {
        let hasChanges = false;
        const next = new Map(prev);
        
        next.forEach((retry, id) => {
          if (retry.state === 'retrying' && retry.countdown > 0) {
            const newCountdown = retry.countdown - 100;
            next.set(id, { ...retry, countdown: Math.max(0, newCountdown) });
            hasChanges = true;
          }
        });
        
        return hasChanges ? next : prev;
      });
    }, 100);
    
    return () => clearInterval(timer);
  }, []);

  if (retries.size === 0) return null;

  return (
    <div className="fixed bottom-4 right-4 z-50 space-y-2">
      {Array.from(retries.values()).map((retry) => (
        <RetryCard key={retry.id} retry={retry} />
      ))}
    </div>
  );
}

function RetryCard({ retry }: { retry: RetryStatus & { countdown: number } }) {
  if (retry.state === 'success') {
    return (
      <Card className="p-4 shadow-lg border-success bg-success/10 w-80 animate-in slide-in-from-bottom-4">
        <div className="flex items-center gap-3">
          <CheckCircle2 className="w-5 h-5 text-success flex-shrink-0" />
          <p className="text-sm font-medium text-foreground">
            {retry.type} submitted successfully!
          </p>
        </div>
      </Card>
    );
  }
  
  if (retry.state === 'failed') {
    return (
      <Card className="p-4 shadow-lg border-destructive bg-destructive/10 w-80 animate-in slide-in-from-bottom-4">
        <div className="flex items-start gap-3">
          <XCircle className="w-5 h-5 text-destructive mt-0.5 flex-shrink-0" />
          <div className="flex-1 space-y-2">
            <p className="text-sm font-medium text-foreground">
              Submission failed
            </p>
            {retry.errorId && (
              <>
                <p className="text-xs text-muted-foreground">
                  Error ID: {retry.errorId}
                </p>
                <Button 
                  size="sm" 
                  variant="outline" 
                  onClick={() => window.location.href = `/admin/error-lookup?id=${retry.errorId}`}
                >
                  View Details
                </Button>
              </>
            )}
          </div>
        </div>
      </Card>
    );
  }
  
  // Retrying state
  const progress = retry.delay > 0 ? ((retry.delay - retry.countdown) / retry.delay) * 100 : 0;
  
  return (
    <Card className="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">
              {retry.attempt}/{retry.maxAttempts}
            </span>
          </div>
          
          <p className="text-xs text-amber-700 dark:text-amber-300">
            Network issue detected. Retrying {retry.type} submission in {Math.ceil(retry.countdown / 1000)}s
          </p>
          
          <Progress value={progress} className="h-1" />
        </div>
      </div>
    </Card>
  );
}
