/**
 * Lightweight confirm dialog and toast system for the plugin admin UI.
 * Replaces window.confirm() and alert() throughout.
 *
 * Usage:
 *   const { confirm, toast, NotifyPortal } = useNotify();
 *   <NotifyPortal />
 *   await confirm({ message: 'Delete this?' })  → boolean
 *   toast({ message: 'Saved!', type: 'success' })
 */

import { useCallback, useState } from 'react';
import { createPortal } from 'react-dom';

interface ConfirmOptions {
  title?: string;
  message: string;
  confirmLabel?: string;
  cancelLabel?: string;
  danger?: boolean;
}

interface ToastOptions {
  message: string;
  type?: 'success' | 'error' | 'info';
  duration?: number;
}

interface ToastItem extends ToastOptions {
  id: number;
}

interface ConfirmState extends ConfirmOptions {
  resolve: (v: boolean) => void;
}

let _toastId = 0;

export function useNotify() {
  const [confirmState, setConfirmState] = useState<ConfirmState | null>(null);
  const [toasts, setToasts] = useState<ToastItem[]>([]);

  const confirm = useCallback((opts: ConfirmOptions): Promise<boolean> => {
    return new Promise((resolve) => {
      setConfirmState({ ...opts, resolve });
    });
  }, []);

  const toast = useCallback((opts: ToastOptions) => {
    const id = ++_toastId;
    setToasts((prev) => [...prev, { ...opts, id }]);
    const duration = opts.duration ?? (opts.type === 'error' ? 5000 : 3000);
    setTimeout(() => {
      setToasts((prev) => prev.filter((t) => t.id !== id));
    }, duration);
  }, []);

  const dismissConfirm = (value: boolean) => {
    confirmState?.resolve(value);
    setConfirmState(null);
  };

  const NotifyPortal = useCallback(() => {
    return createPortal(
      <>
        {confirmState && (
          <div className="cra-dialog-backdrop" onClick={() => dismissConfirm(false)}>
            <div className="cra-dialog-box" onClick={(e) => e.stopPropagation()}>
              {confirmState.title && <p className="cra-dialog-title">{confirmState.title}</p>}
              <p className="cra-dialog-message">{confirmState.message}</p>
              <div className="cra-dialog-actions">
                <button className="cra-btn cra-btn-sm" onClick={() => dismissConfirm(false)}>
                  {confirmState.cancelLabel ?? 'Cancel'}
                </button>
                <button
                  className={`cra-btn cra-btn-sm ${confirmState.danger ? 'cra-btn-danger' : 'cra-btn-primary'}`}
                  onClick={() => dismissConfirm(true)}
                  autoFocus
                >
                  {confirmState.confirmLabel ?? 'Confirm'}
                </button>
              </div>
            </div>
          </div>
        )}

        {toasts.length > 0 && (
          <div className="cra-toast-stack">
            {toasts.map((t) => (
              <div key={t.id} className={`cra-toast cra-toast-${t.type ?? 'info'}`}>
                <span>{t.message}</span>
                <button
                  className="cra-toast-dismiss"
                  onClick={() => setToasts((prev) => prev.filter((x) => x.id !== t.id))}
                >
                  ×
                </button>
              </div>
            ))}
          </div>
        )}
      </>,
      document.body
    );
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [confirmState, toasts]);

  return { confirm, toast, NotifyPortal };
}
