'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { cn } from '@/lib/utils/cn';

export type ToastTone = 'info' | 'success' | 'danger';

export interface ToastOptions {
  /** How long it stays (ms). `null`: until the user closes it. Default 2600 (as CRM.toast). */
  durationMs?: number | null;
  /** A link shown after the message (e.g. the download of a finished export). */
  link?: { label: string; href: string };
  /** G9: one button after the message (the bulk edit's "Undo"); clicking it closes the toast. */
  action?: { label: string; onClick: () => void };
}

interface ToastItem {
  id: number;
  message: string;
  tone: ToastTone;
  leaving: boolean;
  sticky: boolean;
  link?: { label: string; href: string };
  action?: { label: string; onClick: () => void };
}

/** How long a toast stays before it animates out (matches base.js CRM.toast). */
const TOAST_MS = 2600;

/**
 * Bottom toasts, same behaviour as `CRM.toast(msg, type)` in the PHP design.
 * Render `<ToastRegion toasts={toasts} onDone={remove} />` once per page.
 */
/** The most messages on screen at once: more would cover the buttons under them. */
export const MAX_TOASTS = 3;

/**
 * Adds a message. One already on screen with the same words is replaced rather than stacked, and
 * only the newest few stay.
 */
export function addToast<T extends { message: string; tone: string }>(list: T[], next: T): T[] {
  const others = list.filter((t) => t.message !== next.message || t.tone !== next.tone);
  return [...others, next].slice(-MAX_TOASTS);
}

export function useToasts() {
  const [toasts, setToasts] = useState<ToastItem[]>([]);
  const nextId = useRef(0);
  const timers = useRef<number[]>([]);

  useEffect(() => {
    const pending = timers.current;
    return () => pending.forEach((t) => window.clearTimeout(t));
  }, []);

  /** Starts the leave animation; the region removes it when the animation ends. */
  const dismiss = useCallback((id: number) => {
    setToasts((list) => list.map((t) => (t.id === id ? { ...t, leaving: true } : t)));
  }, []);

  const toast = useCallback(
    (message: string, tone: ToastTone = 'success', options: ToastOptions = {}) => {
      const id = ++nextId.current;
      const duration = options.durationMs === undefined ? TOAST_MS : options.durationMs;
      setToasts((list) =>
        addToast(list, {
          id,
          message,
          tone,
          leaving: false,
          sticky: duration === null,
          link: options.link,
          ...(options.action && { action: options.action }),
        }),
      );
      if (duration !== null) timers.current.push(window.setTimeout(() => dismiss(id), duration));
    },
    [dismiss],
  );

  const remove = useCallback((id: number) => {
    setToasts((list) => list.filter((t) => t.id !== id));
  }, []);

  return { toasts, toast, dismiss, remove };
}

export function ToastRegion({
  toasts,
  onDismiss,
  onDone,
}: {
  toasts: ToastItem[];
  onDismiss: (id: number) => void;
  onDone: (id: number) => void;
}) {
  return (
    <div className="toast-region" aria-live="polite" aria-atomic="true">
      {toasts.map((t) => (
        <div
          key={t.id}
          className={cn('toast', `toast--${t.tone}`, t.leaving && 'is-leaving')}
          role="status"
          onAnimationEnd={() => {
            if (t.leaving) onDone(t.id);
          }}
        >
          {t.message}
          {t.link ? (
            <a
              href={t.link.href}
              style={{ color: 'inherit', fontWeight: 700, textDecoration: 'underline' }}
            >
              {t.link.label}
            </a>
          ) : null}
          {t.action ? (
            <button
              type="button"
              className="toast__action"
              onClick={() => {
                t.action!.onClick();
                onDismiss(t.id);
              }}
            >
              {t.action.label}
            </button>
          ) : null}
          {t.sticky ? (
            <button
              type="button"
              aria-label="Close"
              onClick={() => onDismiss(t.id)}
              style={{
                marginLeft: 8,
                background: 'none',
                border: 0,
                color: 'inherit',
                cursor: 'pointer',
                fontSize: 18,
                lineHeight: 1,
              }}
            >
              ×
            </button>
          ) : null}
        </div>
      ))}
    </div>
  );
}
