import { createContext, useCallback, useRef, useState, type ReactNode } from 'react';
import Modal from './Modal';

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

export type ConfirmFn = (options: ConfirmOptions) => Promise<boolean>;

export const ConfirmContext = createContext<ConfirmFn | null>(null);

interface PendingConfirm extends ConfirmOptions {
  resolve: (value: boolean) => void;
}

/**
 * Fournit `useConfirm()` : une fonction `confirm(options)` qui ouvre un dialogue
 * et résout `true`/`false` selon le choix de l'utilisateur. À monter une fois,
 * haut dans l'arbre (cf. main.tsx). Idéal avant une action destructrice (`del`).
 */
export function ConfirmProvider({ children }: { children: ReactNode }) {
  const [pending, setPending] = useState<PendingConfirm | null>(null);
  const pendingRef = useRef<PendingConfirm | null>(null);
  pendingRef.current = pending;

  const confirm = useCallback<ConfirmFn>((options) => {
    return new Promise<boolean>((resolve) => {
      setPending({ ...options, resolve });
    });
  }, []);

  const settle = useCallback((value: boolean) => {
    pendingRef.current?.resolve(value);
    setPending(null);
  }, []);

  return (
    <ConfirmContext.Provider value={confirm}>
      {children}
      {pending && (
        <Modal
          title={pending.title ?? 'Confirmation'}
          onClose={() => settle(false)}
          footer={
            <>
              <button onClick={() => settle(false)}>{pending.cancelLabel ?? 'Annuler'}</button>
              <button className="btn-primary" onClick={() => settle(true)}>
                {pending.confirmLabel ?? 'Confirmer'}
              </button>
            </>
          }
        >
          <p>{pending.message}</p>
        </Modal>
      )}
    </ConfirmContext.Provider>
  );
}
