"use client";

import {
  createContext,
  useContext,
  useState,
  useCallback,
  type ReactNode,
} from "react";

type ToastType = "success" | "error" | "warning" | "info";

interface ToastItem {
  id: string;
  type: ToastType;
  title: string;
  description?: string;
}

interface ToastContextValue {
  toasts: ToastItem[];
  show: (type: ToastType, title: string, description?: string) => void;
  dismiss: (id: string) => void;
}

const ToastContext = createContext<ToastContextValue | null>(null);

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

  const dismiss = useCallback((id: string) => {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }, []);

  const show = useCallback(
    (type: ToastType, title: string, description?: string) => {
      const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
      setToasts((prev) => [...prev, { id, type, title, description }]);
      setTimeout(() => dismiss(id), 5000);
    },
    [dismiss],
  );

  const colorMap: Record<ToastType, string> = {
    success: "var(--color-success)",
    error: "var(--color-danger)",
    warning: "var(--color-warning)",
    info: "var(--color-accent)",
  };

  return (
    <ToastContext.Provider value={{ toasts, show, dismiss }}>
      {children}
      <div
        role="region"
        aria-label="通知"
        aria-live="polite"
        aria-atomic="true"
        style={{
          position: "fixed",
          top: 16,
          right: 16,
          zIndex: 9999,
          display: "flex",
          flexDirection: "column",
          gap: 8,
          maxWidth: 400,
        }}
      >
        {toasts.map((toast) => (
          <button
            key={toast.id}
            type="button"
            style={{
              background: "var(--bg-paper)",
              border: "none",
              borderLeft: `4px solid ${colorMap[toast.type]}`,
              borderRadius: 6,
              padding: "12px 16px",
              boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
              cursor: "pointer",
              textAlign: "left",
              width: "100%",
              display: "block",
            }}
            onClick={() => dismiss(toast.id)}
            aria-label={`${toast.title}${toast.description ? `: ${toast.description}` : ""}`}
          >
            <p
              style={{
                fontWeight: 600,
                fontSize: 14,
                color: "var(--color-ink)",
                margin: 0,
              }}
            >
              {toast.title}
            </p>
            {toast.description && (
              <p
                style={{
                  fontSize: 13,
                  color: "var(--color-ink-muted)",
                  marginTop: 4,
                  margin: 0,
                }}
              >
                {toast.description}
              </p>
            )}
          </button>
        ))}
      </div>
    </ToastContext.Provider>
  );
}

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