import { useEffect, useRef, useState } from 'react'; type Props = { id: number; nombre: string; tienePrestamos?: boolean; }; export default function EliminarMaterial({ id, nombre, tienePrestamos }: Props) { const dialogRef = useRef(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const titleId = `del-mat-${id}`; const open = () => { setError(null); dialogRef.current?.showModal(); }; const close = () => { if (loading) return; dialogRef.current?.close(); }; useEffect(() => { const dlg = dialogRef.current; if (!dlg) return; const onClick = (e: MouseEvent) => { if (e.target === dlg) close(); }; dlg.addEventListener('click', onClick); return () => dlg.removeEventListener('click', onClick); }); const submit = async () => { if (loading) return; setLoading(true); setError(null); try { const res = await fetch(`/api/admin/materiales/${id}`, { method: 'DELETE' }); const json = await res.json().catch(() => ({})); if (!res.ok) throw new Error(json?.error ?? 'No se pudo eliminar'); dialogRef.current?.close(); location.reload(); } catch (err) { setError(err instanceof Error ? err.message : 'Error inesperado'); } finally { setLoading(false); } }; return ( <>

Eliminar material

¿Seguro que quieres eliminar {nombre}? Esta acción no se puede deshacer.

{tienePrestamos && (

Este material tiene préstamos asociados y no podrá eliminarse.

)} {error && (

{error}

)}
); }