'use client';

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

export interface ConfirmOptions {
  title: string;
  message: React.ReactNode;
  confirmLabel?: string;
  /** Red confirm button, for actions that stop or remove something. */
  danger?: boolean;
}

/**
 * An in-app yes / no dialog in place of `window.confirm()` (QA 14 Oct #68: the native pop-up
 * looks foreign and blocks the browser). `await confirm({...})` resolves true on confirm,
 * false on cancel / Esc / backdrop; render `dialog` once in the component.
 *
 * Uses a native `<dialog showModal()>` so it stacks above settings drawers and other
 * top-layer dialogs (a plain `.modal-backdrop` would sit underneath them).
 */
export function useConfirm(): {
  confirm: (options: ConfirmOptions) => Promise<boolean>;
  dialog: React.ReactNode;
} {
  const [options, setOptions] = useState<ConfirmOptions | null>(null);
  const resolver = useRef<((ok: boolean) => void) | null>(null);
  const dialogRef = useRef<HTMLDialogElement>(null);

  const settle = useCallback((ok: boolean) => {
    resolver.current?.(ok);
    resolver.current = null;
    setOptions(null);
  }, []);

  const confirm = useCallback((next: ConfirmOptions) => {
    resolver.current?.(false);
    setOptions(next);
    return new Promise<boolean>((resolve) => {
      resolver.current = resolve;
    });
  }, []);

  const cancel = useCallback(() => settle(false), [settle]);

  useEffect(() => {
    const d = dialogRef.current;
    if (!d) return;
    if (options && !d.open) {
      d.showModal();
    } else if (!options && d.open) {
      d.close();
    }
  }, [options]);

  const dialog = (
    <dialog
      ref={dialogRef}
      className="set-modal"
      id="crmConfirmDialog"
      aria-labelledby="crmConfirmDialog-title"
      onClose={cancel}
      onClick={(e) => {
        if (e.target === e.currentTarget) cancel();
      }}
      // Esc closes this dialog only, not a modal or drawer it was opened from.
      onKeyDown={(e) => {
        if (e.key === 'Escape') e.stopPropagation();
      }}
    >
      <div>
        <div className="set-modal__head">
          <h2 className="set-modal__title" id="crmConfirmDialog-title">
            {options?.title ?? ''}
          </h2>
          <button
            type="button"
            className="icon-btn icon-btn--ghost"
            aria-label="Close"
            onClick={cancel}
          >
            <CrmIcon name="x" className="iconSize-20" />
          </button>
        </div>
        <div className="set-modal__body">
          <p className="crm-mb-0">{options?.message}</p>
        </div>
        <div
          className={cn('set-modal__foot', options?.danger && 'set-modal__foot--danger-confirm')}
        >
          {options?.danger ? (
            <>
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                onClick={() => settle(true)}
                style={{ background: 'var(--danger)', borderColor: 'var(--danger)' }}
              >
                {options.confirmLabel ?? 'Confirm'}
              </button>
              <button type="button" className="btn-crm btn-crm--outline" onClick={cancel}>
                Cancel
              </button>
            </>
          ) : (
            <>
              <button type="button" className="btn-crm btn-crm--outline" onClick={cancel}>
                Cancel
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                onClick={() => settle(true)}
              >
                {options?.confirmLabel ?? 'Confirm'}
              </button>
            </>
          )}
        </div>
      </div>
    </dialog>
  );

  return { confirm, dialog };
}
