import { router } from '@inertiajs/react';
import { showConfirmation, showSuccess, showError, showLoading, updateToast } from '@/lib/toast';

interface UseCrudOperationsProps {
    entityName: string; // Nombre de la entidad (ej: "categoría", "metodología")
    entityNamePlural?: string; // Nombre plural (ej: "categorías", "metodologías")
    basePath: string; // Ruta base (ej: "/categories", "/metodologies")
}

export function useCrudOperations({
    entityName,
    entityNamePlural = `${entityName}s`,
    basePath
}: UseCrudOperationsProps) {

    // Función para eliminar con confirmación
    const handleDelete = (id: number, name: string) => {
        showConfirmation(
            `¿Estás seguro de que quieres eliminar ${entityName.toLowerCase()} "${name}"?`,
            () => {
                router.delete(`${basePath}/${id}`, {
                    onSuccess: () => {
                        showSuccess(`${entityName} eliminada exitosamente`);
                    },
                    onError: () => {
                        showError(`Error al eliminar ${entityName.toLowerCase()}`);
                    }
                });
            }
        );
    };

    // Función para crear con toast de carga
    const handleCreate = (data: any, options?: { onSuccess?: () => void; onError?: () => void }) => {
        const toastId = showLoading(`Creando ${entityName.toLowerCase()}...`);

        router.post(basePath, data, {
            onSuccess: () => {
                updateToast(toastId, 'success', `${entityName} creada exitosamente`);
                options?.onSuccess?.();
            },
            onError: () => {
                updateToast(toastId, 'error', `Error al crear ${entityName.toLowerCase()}`);
                options?.onError?.();
            }
        });
    };

    // Función para actualizar con toast de carga
    const handleUpdate = (id: number, data: any, options?: { onSuccess?: () => void; onError?: () => void }) => {
        const toastId = showLoading(`Actualizando ${entityName.toLowerCase()}...`);

        router.put(`${basePath}/${id}`, data, {
            onSuccess: () => {
                updateToast(toastId, 'success', `${entityName} actualizada exitosamente`);
                options?.onSuccess?.();
            },
            onError: () => {
                updateToast(toastId, 'error', `Error al actualizar ${entityName.toLowerCase()}`);
                options?.onError?.();
            }
        });
    };

    return {
        handleDelete,
        handleCreate,
        handleUpdate,
    };
}
