import { useState } from 'react';
import { Modal } from './Modal';
import { Button } from './Button';

interface ConfirmOptions {
  title: string;
  message: React.ReactNode;
  confirmLabel?: string;
  danger?: boolean;
}

/**
 * Promise-based confirmation using the themed Modal (no native window.confirm).
 *
 *   const { confirm, confirmElement } = useConfirm();
 *   ...
 *   <Button onClick={async () => { if (await confirm({ title, message })) doIt(); }} />
 *   {confirmElement}
 */
export function useConfirm() {
  const [state, setState] = useState<(ConfirmOptions & { resolve: (ok: boolean) => void }) | null>(null);

  const confirm = (opts: ConfirmOptions) =>
    new Promise<boolean>((resolve) => setState({ ...opts, resolve }));

  const settle = (ok: boolean) => {
    state?.resolve(ok);
    setState(null);
  };

  const confirmElement = state ? (
    <Modal
      open
      onClose={() => settle(false)}
      title={state.title}
      className="max-w-md"
      footer={
        <>
          <Button variant="ghost" onClick={() => settle(false)}>Cancel</Button>
          <Button variant={state.danger === false ? 'primary' : 'danger'} onClick={() => settle(true)}>
            {state.confirmLabel ?? 'Delete'}
          </Button>
        </>
      }
    >
      <div className="text-sm text-muted">{state.message}</div>
    </Modal>
  ) : null;

  return { confirm, confirmElement };
}
