import { createContext, PropsWithChildren, useCallback, useContext, useRef, useState } from 'react';
import { ConfirmDialog } from '@/Components/ui/ConfirmDialog';

interface ConfirmOptions {
    title: string;
    description?: string;
    confirmLabel?: string;
}

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

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

export function ConfirmProvider({ children }: PropsWithChildren) {
    const [options, setOptions] = useState<ConfirmOptions | null>(null);
    const resolver = useRef<((value: boolean) => void) | null>(null);

    const confirm = useCallback<ConfirmFn>((opts) => {
        setOptions(opts);
        return new Promise<boolean>((resolve) => {
            resolver.current = resolve;
        });
    }, []);

    const settle = (value: boolean) => {
        resolver.current?.(value);
        resolver.current = null;
        setOptions(null);
    };

    return (
        <ConfirmContext.Provider value={confirm}>
            {children}
            <ConfirmDialog
                isOpen={options !== null}
                onOpenChange={(open) => { if (!open) settle(false); }}
                title={options?.title ?? ''}
                description={options?.description}
                confirmLabel={options?.confirmLabel}
                onConfirm={() => settle(true)}
            />
        </ConfirmContext.Provider>
    );
}

export function useConfirm(): ConfirmFn {
    const ctx = useContext(ConfirmContext);
    if (!ctx) {
        throw new Error('useConfirm must be used within ConfirmProvider');
    }

    return ctx;
}
