import { useEffect, useState } from 'react';
import { X } from 'lucide-react';

export type ToastLevel = 'error' | 'warning' | 'success';

export interface ToastMessage {
  id: number;
  level: ToastLevel;
  text: string;
}

let toastSeq = 0;

export function createToast(level: ToastLevel, text: string): ToastMessage {
  return { id: toastSeq++, level, text };
}

const COLORS: Record<ToastLevel, string> = {
  error: '#c83232',
  warning: '#c8a832',
  success: '#32a852',
};

interface ErrorToastProps {
  toasts: ToastMessage[];
  onDismiss: (id: number) => void;
}

export function ErrorToast({ toasts, onDismiss }: ErrorToastProps) {
  return (
    <div style={{ position: 'absolute', top: 44, right: 8, zIndex: 100, display: 'flex', flexDirection: 'column', gap: 6 }}>
      {toasts.map((t) => (
        <ToastItem key={t.id} toast={t} onDismiss={onDismiss} />
      ))}
    </div>
  );
}

function ToastItem({ toast, onDismiss }: { toast: ToastMessage; onDismiss: (id: number) => void }) {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    // Error toasts stay longer (10s), warnings/success auto-dismiss faster (4s)
    const duration = toast.level === 'error' ? 10000 : 4000;
    const timer = setTimeout(() => {
      setVisible(false);
      setTimeout(() => onDismiss(toast.id), 300);
    }, duration);
    return () => clearTimeout(timer);
  }, [toast.id, toast.level, onDismiss]);

  return (
    <div
      data-testid="error-toast"
      style={{
        background: COLORS[toast.level],
        color: '#fff',
        padding: '8px 14px',
        borderRadius: 4,
        fontSize: 12,
        fontFamily: 'monospace',
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        opacity: visible ? 1 : 0,
        transition: 'opacity 0.3s',
        maxWidth: 400,
      }}
    >
      <span style={{ flex: 1 }}>{toast.text}</span>
      <button
        onClick={() => onDismiss(toast.id)}
        style={{ background: 'none', border: 'none', color: '#fff', cursor: 'pointer', padding: 0 }}
      >
        <X size={14} />
      </button>
    </div>
  );
}
