import { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import type { LucideIcon } from 'lucide-react' import { ICON_OVERRIDES } from '@/components/DeviceRow' import { IconPicker } from '@/components/IconPicker' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select' import { Sheet, SheetContent, SheetHeader, SheetTitle, } from '@/components/ui/sheet' import { Switch } from '@/components/ui/switch' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog' import { cn, fetchJson } from '@/lib/utils' import { useNetPulse } from '@/data/DataProvider' import type { ClientDevice } from '@/pages/devices-data' // #693: el server solo acepta hostnames DNS en la reserva DHCP. Un nombre // visible libre ("TV Salón") viaja vacío y la reserva usa la MAC como name. const DNS_HOSTNAME_RE = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ const asDhcpHostname = (name: string) => name.length > 0 && name.length <= 253 && DNS_HOSTNAME_RE.test(name) ? name : '' export interface DeviceEditSheetProps { open: boolean device: ClientDevice | null isDemo: boolean saving?: boolean onClose: () => void /** Patch absoluto: '' en un campo = volver al valor automático (#797). */ onSave: ( device: ClientDevice, patch: { icon: string; name: string; type: string; notifyOffline: boolean; nameSource: string }, ) => void /** #1145: tras borrar el cliente del registro (el padre cierra y refresca). */ onDeleted?: () => void /** #1151: resto de clientes (para el selector de enlace). */ clients?: ClientDevice[] /** #1151: tras enlazar/desenlazar (el padre cierra y refresca). */ onLinkChanged?: () => void } // #797: tipos válidos del clasificador (paridad con adapters.ValidDeviceTypes // y las claves devices.types.* de los locales). const DEVICE_TYPES = [ 'movil', 'portatil', 'ordenador', 'tablet', 'tv', 'consola', 'camara', 'aspirador', 'videoportero', 'clima', 'caldera', 'placa', 'altavoz', 'servidor', 'iot', 'switch', 'modem', 'desconocido', ] as const export function DeviceEditSheet({ open, device, isDemo, saving, onClose, onSave, onDeleted, clients, onLinkChanged, }: DeviceEditSheetProps) { const { t } = useTranslation() const { refresh } = useNetPulse() const [deleteOpen, setDeleteOpen] = useState(false) const [deleting, setDeleting] = useState(false) const [linkTarget, setLinkTarget] = useState('') const [linkBusy, setLinkBusy] = useState(false) const [icon, setIcon] = useState(device?.iconOverride ?? '') const [notifyOffline, setNotifyOffline] = useState(device?.notifyOffline ?? false) const otherClients = (clients ?? []).filter( (c) => c.mac && c.mac !== device?.mac && c.mac !== device?.id && !(device?.aliasMacs ?? []).includes(c.mac), ) const linkClient = async () => { if (!linkTarget || !device?.mac) return setLinkBusy(true) try { await fetchJson(`/api/devices/${encodeURIComponent(linkTarget)}/link`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ target: device.mac }), }) onLinkChanged?.() onClose() } catch { // fallo silencioso: el botón vuelve a habilitarse } finally { setLinkBusy(false) } } const unlinkAlias = async (alias: string) => { if (!alias) return setLinkBusy(true) try { await fetchJson(`/api/devices/${encodeURIComponent(alias)}/link`, { method: 'DELETE' }) onLinkChanged?.() onClose() } catch { // fallo silencioso } finally { setLinkBusy(false) } } const [name, setName] = useState(device?.nameOverride ?? '') // #2163: fuente de nombre elegida para este cliente ('' = automática). const [nameSource, setNameSource] = useState(device?.nameSourceOverride ?? '') const [devType, setDevType] = useState(device?.typeOverride ?? '') const [reservation, setReservation] = useState<{ reserved: boolean; ip: string; loading: boolean }>({ reserved: false, ip: '', loading: false }) const [reserveDraft, setReserveDraft] = useState(device?.ip ?? '') const [block, setBlock] = useState<{ blocked: boolean; loading: boolean }>({ blocked: false, loading: false }) // #754: dry-run de comandos. Antes de escribir en el router (reservar o // bloquear) se pide el plan al server y se muestra; nada se aplica hasta // la confirmación explícita sobre esos comandos. const [plan, setPlan] = useState<{ host: string; apply: string[]; rollback: string[] } | null>(null) const [planRun, setPlanRun] = useState Promise)>(null) const [planBusy, setPlanBusy] = useState(false) const closePlan = () => { setPlan(null) setPlanRun(null) } const openPlan = async (path: string, body: unknown, run: () => Promise) => { const sep = path.includes('?') ? '&' : '?' const res = await fetchJson<{ host?: string; apply?: string[]; rollback?: string[] }>(path + sep + 'dry_run=1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }) if (!res.ok || !res.data) return false setPlan({ host: res.data.host ?? '', apply: res.data.apply ?? [], rollback: res.data.rollback ?? [] }) setPlanRun(() => run) return true } useEffect(() => { setIcon(device?.iconOverride ?? '') setName(device?.nameOverride ?? '') setDevType(device?.typeOverride ?? '') setNotifyOffline(device?.notifyOffline ?? false) setNameSource(device?.nameSourceOverride ?? '') setReserveDraft(device?.ip ?? '') }, [ device?.id, device?.iconOverride, device?.nameOverride, device?.typeOverride, device?.notifyOffline, device?.nameSourceOverride, device?.ip, ]) useEffect(() => { if (!device || isDemo) return let cancelled = false const load = async () => { setReservation((p) => ({ ...p, loading: true })) setBlock((p) => ({ ...p, loading: true })) const [res, blk] = await Promise.all([ fetchJson<{ reserved: boolean; ip?: string }>(`/api/devices/${encodeURIComponent(device.mac)}/reservation`), fetchJson<{ blocked: boolean }>(`/api/devices/${encodeURIComponent(device.mac)}/block?router=${encodeURIComponent(device.routerId)}`), ]) if (cancelled) return if (res.ok) { setReservation({ reserved: res.data.reserved, ip: res.data.ip ?? '', loading: false }) if (res.data.ip) setReserveDraft(res.data.ip) } else { setReservation({ reserved: false, ip: '', loading: false }) } if (blk.ok) { setBlock({ blocked: blk.data.blocked, loading: false }) } else { setBlock({ blocked: false, loading: false }) } } void load() return () => { cancelled = true } }, [device, isDemo]) const handleSave = () => { if (!device) return onSave(device, { icon, name: name.trim(), type: devType, notifyOffline, nameSource }) } // #800: hostname DNS derivado del nombre visible (input del sheet o nombre // actual). Vacío = el nombre visible no es aplicable como hostname DNS. const appliedHostname = device ? asDhcpHostname(name.trim() || device.name) : '' const selectedIconName = icon || null const PreviewIcon = (selectedIconName ? (ICON_OVERRIDES[selectedIconName] ?? ICON_OVERRIDES['help-circle']) : ICON_OVERRIDES['help-circle']) as LucideIcon return ( !v && onClose()}> {/* #828: cabecera con título para que el X de cierre quede sobre ella (patrón estándar de los sheets) y no montado encima de la tarjeta de vista previa con la MAC. */} {t('devices.edit.title')} {device && (
{/* Vista previa */}
{name.trim() || device.name}
{device.mac}
{/* Nombre visible (#797) */}
setName(e.target.value)} placeholder={device.name} disabled={saving} maxLength={64} className="h-9 rounded-lg border-border bg-elevated text-sm text-text-primary placeholder:text-text-muted focus-visible:border-accent/50" />

{t('devices.edit.nameHint')}

{/* #2163: fuente de nombre elegida para este cliente. Solo se ofrece lo que este cliente tiene de verdad: elegir mDNS en un equipo que no anuncia nada no cambiaría el nombre. */}

{(device.nameCandidates ?? []).length < 2 ? t('devices.edit.nameSourceNone') : t('devices.edit.nameSourceHint')}

{/* Tipo (#797) */}
{/* Icono */}
{/* #1354: alerta opt-in cuando el dispositivo se desconecta */}
{/* #1096: Save/Cancel junto a la zona que editan (nombre, tipo, icono); abajo quedaban lejos, tras Reserva/Bloqueo, que son acciones independientes con sus propios botones. */}
{/* Detalles de red */}
IP
{device.ip}
{t('devices.colBand')}
{device.band === 'cable' ? t('common.cable') : device.band}
{/* Reserva DHCP */}
{reservation.loading && {t('common.loading')}}
{reservation.reserved ? ( <>

{t('devices.edit.reservedAs', { ip: reservation.ip })}

) : (

{t('devices.edit.reserveHint')}

)}
setReserveDraft(e.target.value)} placeholder={device.ip} disabled={reservation.loading} className="h-9 rounded-lg border-border bg-elevated text-sm text-text-primary placeholder:text-text-muted focus-visible:border-accent/50" />
{/* #800: aplicar el nombre visible como hostname de la reserva */}

{appliedHostname ? t('devices.edit.applyNameHint') : t('devices.edit.applyNameInvalid')}

{/* Bloqueo de dispositivo */}
{block.loading && {t('common.loading')}}

{t('devices.edit.blockHint')}

{block.blocked ? t('devices.edit.blocked') : t('devices.edit.allowed')}
{/* Plan de comandos (#754): nada se aplica hasta confirmar aquí */} {plan && (
{t('devices.edit.planTitle', { host: plan.host || device?.routerId || '' })}
                  {plan.apply.length ? plan.apply.join('\n') : t('devices.edit.planNone')}
                
{plan.rollback.length > 0 && (
{t('devices.edit.planRollback')}
                      {plan.rollback.join('\n')}
                    
)}
)} {/* #1151: MACs enlazadas (mismo dispositivo, varias MACs) */} {!isDemo && device?.mac && (
{t('devices.edit.linkedMacs')}
{(device.aliasMacs?.length ?? 0) > 0 && (
    {device.aliasMacs?.map((alias) => (
  • {alias}
  • ))}
)} {otherClients.length > 0 && (
)}
)} {isDemo && (

{t('devices.edit.demoNotice')}

)} {/* #1145: borrado del cliente del registro. Un cliente borrado solo reaparece si se le vuelve a ver en vivo. #1205: el botón solo tiene sentido para clientes offline (los online los re-detecta el siguiente ciclo del poller y parece que "no borra"): para ellos se sugiere Bloquear. */} {!isDemo && device?.mac && device.online === false && (
{t('devices.edit.dangerZone')}

{t('devices.edit.deleteDesc')}

)} {!isDemo && device?.mac && device.online && (
{t('devices.edit.dangerZone')}

{t('devices.edit.deleteOnlineHint')}

)}
)} {/* #1205: el aviso lleva el mismo tinte rojo que la zona que lo abre */} {t('devices.edit.deleteTitle')} {t('devices.edit.deleteConfirmDesc', { name: device?.name || device?.mac || '' })} {t('common.cancel')} { e.preventDefault() if (!device?.mac) return setDeleting(true) try { await fetchJson(`/api/devices/${encodeURIComponent(device.mac)}`, { method: 'DELETE' }) // #1205: refresco inmediato - si no, la fila seguiría en // pantalla hasta el próximo ciclo y parecería que no borra void refresh() setDeleteOpen(false) onDeleted?.() onClose() } catch { // el fallo deja la hoja abierta; el botón vuelve a habilitarse } finally { setDeleting(false) } }} > {deleting ? t('common.loading') : t('devices.edit.delete')}
) }