import { useEffect, useRef } from 'react';
import { CheckCircle, AlertCircle, Info, X } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { ToastItem } from '@/hooks/useToast';

const icons = {
  success: CheckCircle,
  error: AlertCircle,
  info: Info,
};

const styles = {
  success: 'text-green-600 bg-green-50 border-green-200',
  error: 'text-red-600 bg-red-50 border-red-200',
  info: 'text-zinc-600 bg-zinc-50 border-zinc-200',
};

export function ToastContainer({ toasts, dismiss }: { toasts: ToastItem[]; dismiss: (id: number) => void }) {
  return (
    <div className="fixed bottom-6 right-6 z-[100] flex flex-col gap-2 pointer-events-none">
      {toasts.map((t) => (
        <Toast key={t.id} item={t} dismiss={dismiss} />
      ))}
    </div>
  );
}

function Toast({ item, dismiss }: { item: ToastItem; dismiss: (id: number) => void }) {
  const Icon = icons[item.type];
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    ref.current?.animate(
      [
        { opacity: 0, transform: 'translateY(8px)' },
        { opacity: 1, transform: 'translateY(0)' },
      ],
      { duration: 200, fill: 'forwards' }
    );
  }, []);

  return (
    <div
      ref={ref}
      className={cn(
        'pointer-events-auto flex items-center gap-2 px-3.5 py-2.5 rounded-lg border shadow-lg text-sm',
        styles[item.type]
      )}
    >
      <Icon size={15} className="flex-shrink-0" />
      <span className="flex-1">{item.message}</span>
      <button onClick={() => dismiss(item.id)} className="opacity-60 hover:opacity-100 ml-1">
        <X size={13} />
      </button>
    </div>
  );
}
