import React, { useEffect, useState } from 'react';
import { CheckCircle, XCircle, Info, AlertTriangle, X } from 'lucide-react';

export type ToastType = 'success' | 'error' | 'info' | 'warning';

export interface Toast {
  id: string;
  type: ToastType;
  message: string;
  duration?: number;
}

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

const toastIcons: Record<ToastType, React.ReactNode> = {
  success: <CheckCircle className="h-5 w-5" />,
  error: <XCircle className="h-5 w-5" />,
  info: <Info className="h-5 w-5" />,
  warning: <AlertTriangle className="h-5 w-5" />,
};

const toastStyles: Record<ToastType, { border: string; bg: string; text: string; icon: string }> = {
  success: {
    border: 'border-[var(--term-status-success-border)]',
    bg: 'bg-[var(--term-status-success)]',
    text: 'text-positive',
    icon: 'text-positive',
  },
  error: {
    border: 'border-[var(--term-status-error-border)]',
    bg: 'bg-[var(--term-status-error)]',
    text: 'text-negative',
    icon: 'text-negative',
  },
  info: {
    border: 'border-[var(--term-status-info-border)]',
    bg: 'bg-[var(--term-status-info)]',
    text: 'text-[var(--term-status-info-strong)]',
    icon: 'text-[var(--term-status-info-strong)]',
  },
  warning: {
    border: 'border-[var(--term-status-warning-border)]',
    bg: 'bg-[var(--term-status-warning)]',
    text: 'text-warning',
    icon: 'text-warning',
  },
};

const ToastItem: React.FC<ToastItemProps> = ({ toast, onDismiss }) => {
  const [progress, setProgress] = useState(100);
  const duration = toast.duration ?? 5000;

  useEffect(() => {
    const startTime = Date.now();
    const interval = 50;

    const timer = setInterval(() => {
      const elapsed = Date.now() - startTime;
      const remaining = Math.max(0, 100 - (elapsed / duration) * 100);
      setProgress(remaining);

      if (remaining === 0) {
        onDismiss(toast.id);
      }
    }, interval);

    return () => clearInterval(timer);
  }, [toast.id, duration, onDismiss]);

  const styles = toastStyles[toast.type];

  return (
    <div
      className={`relative overflow-hidden rounded border ${styles.border} ${styles.bg} px-4 py-3 shadow-lg transition-all`}
      role="alert"
      aria-live="polite"
    >
      <div className="flex items-start gap-3">
        <span className={styles.icon}>{toastIcons[toast.type]}</span>
        <div className="flex-1">
          <p className={`text-sm font-mono ${styles.text}`}>{toast.message}</p>
        </div>
        <button
          type="button"
          onClick={() => onDismiss(toast.id)}
          className={`text-xs font-mono opacity-60 transition-opacity hover:opacity-100 ${styles.text}`}
          aria-label="Dismiss notification"
        >
          <X className="h-4 w-4" />
        </button>
      </div>
      <div className="absolute bottom-0 left-0 h-0.5 bg-current opacity-30">
        <div
          className="h-full"
          style={{
            width: `${progress}%`,
            transition: 'width 50ms linear',
          }}
        />
      </div>
    </div>
  );
};

interface ToastContainerProps {
  toasts: Toast[];
  onDismiss: (id: string) => void;
}

export const ToastContainer: React.FC<ToastContainerProps> = ({ toasts, onDismiss }) => {
  if (toasts.length === 0) return null;

  return (
    <div className="fixed bottom-4 right-4 z-50 flex max-w-sm flex-col gap-2">
      {toasts.map((toast) => (
        <ToastItem key={toast.id} toast={toast} onDismiss={onDismiss} />
      ))}
    </div>
  );
};
