'use client';

import { createContext, useCallback, useContext, useState } from 'react';
import { CheckCircle2, XCircle, Info, X } from 'lucide-react';

type ToastKind = 'success' | 'error' | 'info';
type Toast = { id: number; kind: ToastKind; message: string };

type ToastContextValue = { show: (kind: ToastKind, message: string) => void };
const ToastContext = createContext<ToastContextValue | null>(null);

const STYLES: Record<ToastKind, { bg: string; icon: React.ElementType }> = {
  success: { bg: 'bg-green-600', icon: CheckCircle2 },
  error: { bg: 'bg-brand-red', icon: XCircle },
  info: { bg: 'bg-brand-charcoal', icon: Info },
};

let nextId = 1;

export function ToastProvider({ children }: { children: React.ReactNode }) {
  const [toasts, setToasts] = useState<Toast[]>([]);

  const show = useCallback((kind: ToastKind, message: string) => {
    const id = nextId++;
    setToasts((t) => [...t, { id, kind, message }]);
    setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 3500);
  }, []);

  const dismiss = (id: number) => setToasts((t) => t.filter((x) => x.id !== id));

  return (
    <ToastContext.Provider value={{ show }}>
      {children}
      <div className="fixed top-4 right-4 z-50 flex flex-col gap-2 w-[320px]">
        {toasts.map((t) => {
          const { bg, icon: Icon } = STYLES[t.kind];
          return (
            <div
              key={t.id}
              className={`${bg} text-white rounded-lg shadow-lg px-4 py-3 flex items-start gap-2 animate-slideInRight`}
            >
              <Icon size={16} className="mt-0.5 shrink-0" />
              <p className="text-xs flex-1">{t.message}</p>
              <button onClick={() => dismiss(t.id)} className="text-white/70 hover:text-white shrink-0">
                <X size={14} />
              </button>
            </div>
          );
        })}
      </div>
    </ToastContext.Provider>
  );
}

export function useToast() {
  const ctx = useContext(ToastContext);
  if (!ctx) throw new Error('useToast must be used within ToastProvider');
  return ctx;
}
