import { useEffect, type HTMLAttributes } from "react";
import { createPortal } from "react-dom";
import { cn } from "./cn.js";
import { Icon, type IconName } from "./Icon.js";

export type ToastTone = "success" | "error" | "warning" | "info" | "loading";

export type ToastItem = {
  id: string;
  tone: ToastTone;
  title: string;
  description?: string;
  durationMs?: number | null;
};

const toastIcons: Record<ToastTone, IconName> = {
  success: "check",
  error: "alert",
  warning: "alert",
  info: "activity",
  loading: "refresh",
};

export interface ToastCardProps extends HTMLAttributes<HTMLDivElement> {
  item: ToastItem;
  onDismiss?: (id: string) => void;
}

export function ToastCard({ item, onDismiss, className, ...props }: ToastCardProps) {
  return (
    <div
      className={cn("nodedc-toast nodedc-glass-material nodedc-material-rim", className)}
      data-tone={item.tone}
      role={item.tone === "error" ? "alert" : "status"}
      {...props}
    >
      <span className="nodedc-toast__icon" aria-hidden="true"><Icon name={toastIcons[item.tone]} /></span>
      <span className="nodedc-toast__copy">
        <strong>{item.title}</strong>
        {item.description ? <small>{item.description}</small> : null}
      </span>
      {onDismiss ? (
        <button type="button" className="nodedc-toast__dismiss" aria-label="Закрыть уведомление" onClick={() => onDismiss(item.id)}>
          <Icon name="close" />
        </button>
      ) : null}
    </div>
  );
}

export function ToastStack({ items, onDismiss }: { items: ToastItem[]; onDismiss: (id: string) => void }) {
  useEffect(() => {
    const timers = items.flatMap((item) => {
      const duration = item.durationMs === undefined ? 4200 : item.durationMs;
      return typeof duration === "number" && duration > 0
        ? [window.setTimeout(() => onDismiss(item.id), duration)]
        : [];
    });
    return () => timers.forEach((timer) => window.clearTimeout(timer));
  }, [items, onDismiss]);

  if (typeof document === "undefined" || items.length === 0) return null;
  return createPortal(
    <div className="nodedc-toast-viewport nodedc-ui-root" aria-live="polite" aria-relevant="additions removals">
      {items.map((item) => <ToastCard key={item.id} item={item} onDismiss={onDismiss} />)}
    </div>,
    document.body,
  );
}
