import { useEffect, useRef, useState } from 'react'; import { toast, toastAfterReload } from '@/lib/toast'; type Props = { material: { id: number; nombre: string; cantidad_disponible: number; }; }; export default function SolicitarModal({ material }: Props) { const dialogRef = useRef(null); const firstFieldRef = useRef(null); const [cantidad, setCantidad] = useState(1); const [notas, setNotas] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [ok, setOk] = useState(false); const titleId = `solicitar-title-${material.id}`; const open = () => { setError(null); setOk(false); setCantidad(1); setNotas(''); dialogRef.current?.showModal(); queueMicrotask(() => firstFieldRef.current?.focus()); }; const close = () => { if (loading) return; dialogRef.current?.close(); }; // Cerrar al click en backdrop 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 (e: React.FormEvent) => { e.preventDefault(); if (loading) return; setLoading(true); setError(null); try { const res = await fetch('/api/prestamos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ material_id: material.id, cantidad, notas }), }); const json = await res.json().catch(() => ({})); if (!res.ok) { throw new Error(json?.error ?? 'No se pudo enviar la solicitud'); } setOk(true); toastAfterReload({ kind: 'success', title: 'Solicitud enviada', description: `${material.nombre} · pendiente de aprobación`, }); setTimeout(() => { dialogRef.current?.close(); location.reload(); }, 800); } catch (err) { const msg = err instanceof Error ? err.message : 'Error inesperado'; setError(msg); toast({ kind: 'error', title: 'No se pudo enviar', description: msg }); } finally { setLoading(false); } }; const disabled = material.cantidad_disponible === 0; return ( <>

Solicitar: {material.nombre}

Disponibles: {material.cantidad_disponible}

setCantidad(Math.max(1, Math.min(material.cantidad_disponible, Number(e.target.value) || 1)))} style={{ fontVariantNumeric: 'tabular-nums' }} />