import { useEffect, useState, useCallback } from 'react';
import { X, CheckCircle, AlertCircle, AlertTriangle, Info } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Card } from '@/components/ui/card';

export interface Toast {
  id: string;
  message: string;
  type?: 'success' | 'error' | 'warning' | 'info';
  duration?: number;
}

export interface ToastProps {
  toast: Toast;
  onDismiss: (id: string) => void;
}

const TOAST_ICONS = {
  success: CheckCircle,
  error: AlertCircle,
  warning: AlertTriangle,
  info: Info,
};

const TOAST_VARIANTS = {
  success: 'border-lime-500/30 bg-lime-500/10 text-lime-500',
  error: 'border-destructive/30 bg-destructive/10 text-destructive',
  warning: 'border-warning/30 bg-warning/10 text-warning',
  info: 'border-info/30 bg-info/10 text-info',
};

const DEFAULT_DURATION = 5000;

export function ToastComponent({ toast, onDismiss }: ToastProps) {
  const [isVisible, setIsVisible] = useState(false);
  const [isLeaving, setIsLeaving] = useState(false);

  const handleDismiss = useCallback(() => {
    setIsLeaving(true);
    setTimeout(() => {
      onDismiss(toast.id);
    }, 300);
  }, [toast.id, onDismiss]);

  useEffect(() => {
    // Reveal
    requestAnimationFrame(() => setIsVisible(true));

    // Auto-dismiss
    const duration = toast.duration ?? DEFAULT_DURATION;
    let dismissTimer: NodeJS.Timeout | null = null;
    if (duration > 0) {
      dismissTimer = setTimeout(() => {
        handleDismiss();
      }, duration);
    }

    return () => {
      if (dismissTimer) clearTimeout(dismissTimer);
    };
  }, [toast.duration, toast.id, handleDismiss]);

  const Icon = toast.type ? TOAST_ICONS[toast.type] : Info;
  const variantClass = toast.type ? TOAST_VARIANTS[toast.type] : TOAST_VARIANTS.info;

  return (
    <Card
      variant="glass"
      className={cn(
        'relative flex min-w-[320px] max-w-sm items-start gap-4 p-4 shadow-[0_4px_20px_rgba(0,0,0,0.2)] transition-all duration-300 transform',
        variantClass,
        isVisible && !isLeaving
          ? 'opacity-100 translate-x-0 translate-y-0 scale-100'
          : 'opacity-0 translate-x-full scale-95',
        "backdrop-blur-xl" // Ensure glass effect is strong
      )}
      role="alert"
      data-testid="toast-alert"
      aria-live="polite"
    >
      <Icon className="h-5 w-5 flex-shrink-0 animate-[pulse-ring_2s_infinite]" />
      <div className="flex-1">
        <p className="text-sm font-medium leading-relaxed font-sans">{toast.message}</p>
      </div>
      <button
        onClick={handleDismiss}
        className="flex-shrink-0 rounded-md p-1 opacity-60 transition-opacity hover:opacity-100 hover:bg-black/10 focus:outline-none focus:ring-1 focus:ring-current"
        aria-label="Close"
      >
        <X className="h-4 w-4" />
      </button>

      {/* Progress Bar (Optional Visual Cue) */}
      <div className={cn(
        "absolute bottom-0 left-0 h-0.5 bg-current opacity-20 transition-all ease-linear",
        isVisible && !isLeaving ? "w-full" : "w-0"
      )}
        style={{ transitionDuration: `${(toast.duration || DEFAULT_DURATION) - 300}ms` }}
      />
    </Card>
  );
}
