import React, { createContext, useCallback, useContext, useRef, useState } from 'react';
import { ConfirmationModal, ConfirmationVariant } from '../components/ConfirmationModal';

interface ConfirmOptions {
  confirmText?: string;
  cancelText?: string;
  variant?: ConfirmationVariant;
}

interface PendingConfirm {
  title: string;
  message: string;
  options: ConfirmOptions;
  resolve: (value: boolean) => void;
}

interface ConfirmationApi {
  /**
   * Open the confirmation modal and resolve to `true` when the user confirms,
   * `false` when they cancel (X button, backdrop click, or Cancel button).
   */
  confirm: (title: string, message: string, options?: ConfirmOptions) => Promise<boolean>;
}

const ConfirmationContext = createContext<ConfirmationApi | null>(null);

export const ConfirmationProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [pending, setPending] = useState<PendingConfirm | null>(null);
  // Ref tracks the live resolver so handlers always close over the latest call,
  // even if the user spam-clicks (defensive — modal blocks input while open).
  const pendingRef = useRef<PendingConfirm | null>(null);

  const confirm = useCallback((title: string, message: string, options: ConfirmOptions = {}) => {
    return new Promise<boolean>((resolve) => {
      const next: PendingConfirm = { title, message, options, resolve };
      pendingRef.current = next;
      setPending(next);
    });
  }, []);

  const handleConfirm = useCallback(() => {
    pendingRef.current?.resolve(true);
    pendingRef.current = null;
    setPending(null);
  }, []);

  const handleCancel = useCallback(() => {
    pendingRef.current?.resolve(false);
    pendingRef.current = null;
    setPending(null);
  }, []);

  // Stable reference for consumers
  const api = useRef<ConfirmationApi>({ confirm }).current;

  return (
    <ConfirmationContext.Provider value={api}>
      {children}
      <ConfirmationModal
        isOpen={pending !== null}
        title={pending?.title ?? ''}
        message={pending?.message ?? ''}
        confirmText={pending?.options.confirmText}
        cancelText={pending?.options.cancelText}
        variant={pending?.options.variant}
        onConfirm={handleConfirm}
        onCancel={handleCancel}
      />
    </ConfirmationContext.Provider>
  );
};

export const useConfirmation = (): ConfirmationApi => {
  const ctx = useContext(ConfirmationContext);
  if (!ctx) throw new Error('useConfirmation must be used within ConfirmationProvider');
  return ctx;
};
