import { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { Loader2, Trash2, Activity, Cpu, HardDrive, Thermometer, Wifi, WifiOff, AlertTriangle, Info, CheckCircle2, XCircle, Clock, Download, Monitor, RefreshCw, RotateCw, Power, } from 'lucide-react'; import { spoolbuddyApi, type SpoolBuddyDevice } from '../api/client'; import { Card, CardContent, CardHeader } from './Card'; import { Button } from './Button'; import { ConfirmModal } from './ConfirmModal'; import { useToast } from '../contexts/ToastContext'; import { formatRelativeTime } from '../utils/date'; function formatUptime(seconds: number): string { if (seconds < 60) return `${seconds}s`; const m = Math.floor(seconds / 60); if (m < 60) return `${m}m`; const h = Math.floor(m / 60); const remM = m % 60; if (h < 24) return remM ? `${h}h ${remM}m` : `${h}h`; const d = Math.floor(h / 24); const remH = h % 24; return remH ? `${d}d ${remH}h` : `${d}d`; } function formatMB(mb?: number): string { if (mb === undefined || mb === null) return '—'; if (mb >= 1024) return `${(mb / 1024).toFixed(1)} GB`; return `${Math.round(mb)} MB`; } interface DeviceCardProps { device: SpoolBuddyDevice; onUnregister: (device: SpoolBuddyDevice) => void; isDeleting: boolean; } type ActionKey = 'update' | 'restart_browser' | 'restart_daemon' | 'reboot' | 'shutdown'; function DeviceCard({ device, onUnregister, isDeleting }: DeviceCardProps) { const { t } = useTranslation(); const { showToast } = useToast(); const stats = device.system_stats; const mem = stats?.memory; const disk = stats?.disk; const online = device.online; const [pendingAction, setPendingAction] = useState(null); const [busyAction, setBusyAction] = useState(null); const runAction = async (action: ActionKey) => { setBusyAction(action); try { if (action === 'update') { await spoolbuddyApi.triggerUpdate(device.device_id); } else { await spoolbuddyApi.systemCommand(device.device_id, action); } showToast(t('settings.spoolbuddy.commandQueued'), 'success'); } catch (err) { const msg = err instanceof Error ? err.message : t('settings.spoolbuddy.commandError'); showToast(msg, 'error'); } finally { setBusyAction(null); setPendingAction(null); } }; const actions: { key: ActionKey; label: string; icon: typeof Download; variant?: 'danger' }[] = [ { key: 'update', label: t('settings.spoolbuddy.update'), icon: Download }, { key: 'restart_browser', label: t('settings.spoolbuddy.restartBrowser'), icon: Monitor }, { key: 'restart_daemon', label: t('settings.spoolbuddy.restartDaemon'), icon: RefreshCw }, { key: 'reboot', label: t('settings.spoolbuddy.reboot'), icon: RotateCw }, { key: 'shutdown', label: t('settings.spoolbuddy.shutdown'), icon: Power, variant: 'danger' }, ]; const confirmTitles: Record = { update: t('settings.spoolbuddy.updateConfirmTitle'), restart_browser: t('settings.spoolbuddy.restartBrowserConfirmTitle'), restart_daemon: t('settings.spoolbuddy.restartDaemonConfirmTitle'), reboot: t('settings.spoolbuddy.rebootConfirmTitle'), shutdown: t('settings.spoolbuddy.shutdownConfirmTitle'), }; const confirmBodies: Record = { update: t('settings.spoolbuddy.updateConfirmBody', { hostname: device.hostname }), restart_browser: t('settings.spoolbuddy.restartBrowserConfirmBody', { hostname: device.hostname }), restart_daemon: t('settings.spoolbuddy.restartDaemonConfirmBody', { hostname: device.hostname }), reboot: t('settings.spoolbuddy.rebootConfirmBody', { hostname: device.hostname }), shutdown: t('settings.spoolbuddy.shutdownConfirmBody', { hostname: device.hostname }), }; return (

{device.hostname}

{online ? : } {online ? t('settings.spoolbuddy.online') : t('settings.spoolbuddy.offline')}

{device.device_id}

{/* Connection */}
{t('settings.spoolbuddy.ipAddress')}
{device.ip_address}
{t('settings.spoolbuddy.firmware')}
{device.firmware_version ?? '—'}
{t('settings.spoolbuddy.lastSeen')}
{device.last_seen ? formatRelativeTime(device.last_seen) : t('settings.spoolbuddy.never')}
{t('settings.spoolbuddy.daemonUptime')}
{formatUptime(device.uptime_s)}
{/* Action buttons */}
{actions.map(({ key, label, icon: Icon, variant }) => ( ))}
{/* Hardware flags */}
{device.nfc_ok ? ( ) : ( )} {t('settings.spoolbuddy.nfc')} {device.nfc_reader_type && ({device.nfc_reader_type})} {device.scale_ok ? ( ) : ( )} {t('settings.spoolbuddy.scale')}
{/* System stats */} {stats && (
{stats.cpu_temp_c !== undefined && (
{t('settings.spoolbuddy.cpuTemp')}
{stats.cpu_temp_c.toFixed(1)}°C
)} {stats.load_avg && stats.load_avg.length > 0 && (
{t('settings.spoolbuddy.cpuLoad')}
{stats.load_avg[0].toFixed(2)} {stats.cpu_count ? ` / ${stats.cpu_count} (${Math.round((stats.load_avg[0] / stats.cpu_count) * 100)}%)` : ''}
)} {mem && mem.percent !== undefined && (
{t('settings.spoolbuddy.memory')}
{mem.percent.toFixed(0)}% ({formatMB(mem.used_mb)} / {formatMB(mem.total_mb)})
)} {disk && disk.percent !== undefined && (
{t('settings.spoolbuddy.disk')}
{disk.percent.toFixed(0)}% ({disk.used_gb?.toFixed(1)} / {disk.total_gb?.toFixed(1)} GB)
)} {stats.system_uptime_s !== undefined && (
{t('settings.spoolbuddy.systemUptime')}
{formatUptime(stats.system_uptime_s)}
)}
{stats.os && (
{[stats.os.os, stats.os.kernel, stats.os.arch, stats.os.python && `Python ${stats.os.python}`] .filter(Boolean) .join(' · ')}
)}
)}
{pendingAction && ( runAction(pendingAction)} onCancel={() => setPendingAction(null)} /> )}
); } export function SpoolBuddySettings() { const { t } = useTranslation(); const queryClient = useQueryClient(); const { showToast } = useToast(); const [pendingDelete, setPendingDelete] = useState(null); const { data: devices = [], isLoading } = useQuery({ queryKey: ['spoolbuddy-devices'], queryFn: () => spoolbuddyApi.getDevices(), refetchInterval: 15000, }); const deleteMutation = useMutation({ mutationFn: (deviceId: string) => spoolbuddyApi.deleteDevice(deviceId), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['spoolbuddy-devices'] }); showToast(t('settings.spoolbuddy.unregisterSuccess'), 'success'); setPendingDelete(null); }, onError: (err: Error) => { showToast(err.message || t('settings.spoolbuddy.unregisterError'), 'error'); }, }); if (isLoading) { return ( ); } const hasDuplicates = devices.length > 1; return (

{t('settings.spoolbuddy.infoTitle')}

{t('settings.spoolbuddy.infoBody')}

{hasDuplicates && (

{t('settings.spoolbuddy.duplicatesTitle', { count: devices.length })}

{t('settings.spoolbuddy.duplicatesBody')}

)} {devices.length === 0 ? ( {t('settings.spoolbuddy.empty')} ) : (
{devices.map((device) => ( ))}
)} {pendingDelete && ( deleteMutation.mutate(pendingDelete.device_id)} onCancel={() => setPendingDelete(null)} /> )}
); }