import { useState } from 'react';
import { ConfirmDialog } from '@/components/dialogs';

type DeleteConfirmDialogProps<T> = {
    target: T | null;
    onOpenChange: (open: boolean) => void;
    title: string;
    description?: string | ((target: T) => string);
    confirmLabel?: string;
    variant?: 'default' | 'destructive';
    onConfirm: () => void;
};

export function DeleteConfirmDialog<T>({
    target,
    onOpenChange,
    title,
    description,
    confirmLabel = 'Hapus',
    variant,
    onConfirm,
}: DeleteConfirmDialogProps<T>) {
    const [loading, setLoading] = useState(false);

    function handleConfirm() {
        setLoading(true);
        onConfirm();
    }

    return (
        <ConfirmDialog
            open={target !== null}
            onOpenChange={(open) => {
                if (!open) {
                    setLoading(false);
                }
                onOpenChange(open);
            }}
            title={title}
            description={
                typeof description === 'function' && target
                    ? description(target)
                    : typeof description === 'string'
                      ? description
                      : ''
            }
            confirmLabel={confirmLabel}
            variant={variant}
            onConfirm={handleConfirm}
            loading={loading}
        />
    );
}
