import React, { createContext, useContext, useState, ReactNode } from 'react';
import ConfirmDialog from '../components/ConfirmDialog';

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

interface ConfirmContextType {
    confirm: (options: ConfirmOptions | string) => Promise<boolean>;
}

const ConfirmContext = createContext<ConfirmContextType | undefined>(undefined);

export const useConfirm = () => {
    const context = useContext(ConfirmContext);
    if (!context) {
        throw new Error('useConfirm must be used within a ConfirmProvider');
    }
    return context;
};

interface ConfirmProviderProps {
    children: ReactNode;
}

export const ConfirmProvider: React.FC<ConfirmProviderProps> = ({ children }) => {
    const [options, setOptions] = useState<ConfirmOptions | null>(null);
    const [resolveRef, setResolveRef] = useState<((value: boolean) => void) | null>(null);

    const confirm = (opts: ConfirmOptions | string): Promise<boolean> => {
        return new Promise((resolve) => {
            if (typeof opts === 'string') {
                setOptions({ message: opts });
            } else {
                setOptions(opts);
            }
            setResolveRef(() => resolve);
        });
    };

    const handleConfirm = () => {
        if (resolveRef) resolveRef(true);
        setOptions(null);
        setResolveRef(null);
    };

    const handleCancel = () => {
        if (resolveRef) resolveRef(false);
        setOptions(null);
        setResolveRef(null);
    };

    return (
        <ConfirmContext.Provider value={{ confirm }}>
            {children}
            {options && (
                <ConfirmDialog
                    isOpen={!!options}
                    title={options.title}
                    message={options.message}
                    confirmLabel={options.confirmLabel}
                    cancelLabel={options.cancelLabel}
                    onConfirm={handleConfirm}
                    onCancel={handleCancel}
                />
            )}
        </ConfirmContext.Provider>
    );
};
