import { useState, useCallback, useRef } from 'react';

interface ConfirmState {
  isOpen: boolean;
  title: string;
  message: string;
}

export function useConfirm() {
  const [state, setState] = useState<ConfirmState>({
    isOpen: false,
    title: '',
    message: '',
  });

  const resolveRef = useRef<((value: boolean) => void) | null>(null);

  const confirm = useCallback((title: string, message: string): Promise<boolean> => {
    setState({ isOpen: true, title, message });
    return new Promise<boolean>((resolve) => {
      resolveRef.current = resolve;
    });
  }, []);

  const handleConfirm = useCallback(() => {
    setState({ isOpen: false, title: '', message: '' });
    resolveRef.current?.(true);
    resolveRef.current = null;
  }, []);

  const handleCancel = useCallback(() => {
    setState({ isOpen: false, title: '', message: '' });
    resolveRef.current?.(false);
    resolveRef.current = null;
  }, []);

  return {
    ...state,
    confirm,
    handleConfirm,
    handleCancel,
  };
}
