import { createContext, useCallback, useContext, useRef, useState, type ReactNode } from "react";
import { CheckCircle2, AlertTriangle, Info, X } from "lucide-react";
import { cn } from "./cn";

type ToastTone = "success" | "error" | "info";
interface Toast {
  id: number;
  tone: ToastTone;
  msg: string;
}

interface ToastCtx {
  push: (tone: ToastTone, msg: string) => void;
}

const Ctx = createContext<ToastCtx>({ push: () => {} });

// useToast 在任意组件里弹出全局通知。
export function useToast() {
  return useContext(Ctx);
}

const icons = { success: CheckCircle2, error: AlertTriangle, info: Info };
const accent = {
  success: "text-success",
  error: "text-danger",
  info: "text-accent-400",
};

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

  const push = useCallback((tone: ToastTone, msg: string) => {
    const id = ++seq.current;
    setToasts((t) => [...t, { id, tone, msg }]);
    setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 4200);
  }, []);

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

  return (
    <Ctx.Provider value={{ push }}>
      {children}
      <div className="pointer-events-none fixed bottom-4 right-4 z-50 flex w-80 flex-col gap-2">
        {toasts.map((t) => {
          const Icon = icons[t.tone];
          return (
            <div
              key={t.id}
              className="pointer-events-auto flex items-start gap-2.5 rounded-lg border border-line bg-ink-850 px-3 py-2.5 shadow-card"
            >
              <Icon className={cn("mt-0.5 h-4 w-4 shrink-0", accent[t.tone])} strokeWidth={2} />
              <span className="flex-1 text-xs leading-relaxed text-slate-200">{t.msg}</span>
              <button onClick={() => dismiss(t.id)} className="text-slate-600 hover:text-slate-300">
                <X className="h-3.5 w-3.5" />
              </button>
            </div>
          );
        })}
      </div>
    </Ctx.Provider>
  );
}
