import { useEffect, useRef, useState } from 'react'; import { toastAfterReload } from '@/lib/toast'; type Props = { profile: { id: string; nombre?: string | null; email: string }; adminSelf: boolean; }; export default function BanearForm({ profile, adminSelf }: Props) { const dialogRef = useRef(null); const firstFieldRef = useRef(null); const errorRef = useRef(null); const [razon, setRazon] = useState(''); const [expiresAt, setExpiresAt] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const titleId = `banear-${profile.id}`; const label = profile.nombre?.trim() || profile.email; const open = () => { if (adminSelf) return; setError(null); setRazon(''); setExpiresAt(''); dialogRef.current?.showModal(); queueMicrotask(() => firstFieldRef.current?.focus()); }; 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); }); useEffect(() => { if (error) errorRef.current?.focus(); }, [error]); const submit = async (e: React.FormEvent) => { e.preventDefault(); if (loading) return; const trimmed = razon.trim(); if (trimmed.length < 5) { setError('La razón debe tener al menos 5 caracteres'); return; } setLoading(true); setError(null); try { const payload: { profile_id: string; razon: string; expires_at?: string } = { profile_id: profile.id, razon: trimmed, }; if (expiresAt) { payload.expires_at = new Date(expiresAt + 'T23:59:59').toISOString(); } const res = await fetch('/api/admin/baneos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }); const json = await res.json().catch(() => ({})); if (!res.ok) throw new Error(json?.error ?? 'No se pudo banear'); toastAfterReload({ title: 'Usuario baneado', description: label, kind: 'success', }); dialogRef.current?.close(); location.reload(); } catch (err) { setError(err instanceof Error ? err.message : 'Error inesperado'); } finally { setLoading(false); } }; return ( <>

Banear a {label}

El usuario no podrá acceder al sistema hasta ser desbaneado.