import { useState, useEffect, useMemo, useRef } from 'react';
import { useOutletContext } from 'react-router-dom';
import { useQuery, useQueries } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import type { SpoolBuddyOutletContext } from '../../components/spoolbuddy/SpoolBuddyLayout';
import { api, type InventorySpool, type Printer, type PrinterStatus } from '../../api/client';
import { useToast } from '../../contexts/ToastContext';
import { SpoolIcon } from '../../components/spoolbuddy/SpoolIcon';
import { SpoolInfoCard, UnknownTagCard } from '../../components/spoolbuddy/SpoolInfoCard';
import { AssignToAmsModal } from '../../components/spoolbuddy/AssignToAmsModal';
import { LinkSpoolModal } from '../../components/spoolbuddy/LinkSpoolModal';
function normalizeHexTag(value: string | null | undefined): string {
if (!value) return '';
return value.replace(/[^0-9a-f]/gi, '').toUpperCase();
}
function tagsEquivalent(a: string | null | undefined, b: string | null | undefined): boolean {
const aNorm = normalizeHexTag(a);
const bNorm = normalizeHexTag(b);
if (!aNorm || !bNorm) return false;
if (aNorm === bNorm) return true;
// Some readers report shortened UID forms.
return aNorm.endsWith(bNorm) || bNorm.endsWith(aNorm);
}
// Color palette for the cycling spool animation
const SPOOL_COLORS = [
'#00AE42', '#FF6B35', '#3B82F6', '#EF4444', '#A855F7',
'#FBBF24', '#14B8A6', '#EC4899', '#F97316', '#22C55E',
];
// --- Idle state with slow color-cycling spool ---
function IdleSpool() {
const { t } = useTranslation();
const [colorIndex, setColorIndex] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setColorIndex((prev) => (prev + 1) % SPOOL_COLORS.length);
}, 5000);
return () => clearInterval(interval);
}, []);
const currentColor = SPOOL_COLORS[colorIndex];
return (
{/* Spool with single subtle NFC ring */}
{/* Static NFC wave rings */}
{/* Spool icon with slow color transition */}
{/* Text content */}
{t('spoolbuddy.dashboard.readyToScan', 'Ready to scan')}
{t('spoolbuddy.dashboard.idleMessage', 'Place a spool on the scale to identify it')}
{/* Subtle hint */}
{t('spoolbuddy.dashboard.nfcHint', 'NFC tag will be read automatically')}
);
}
// --- Offline state ---
function DeviceOfflineState() {
const { t } = useTranslation();
return (
{/* Offline icon */}
{t('spoolbuddy.status.deviceOffline', 'Device Offline')}
{t('spoolbuddy.status.connectDisplay', 'Connect the SpoolBuddy display to scan spools')}
{t('spoolbuddy.status.waitingConnection', 'Waiting for device connection...')}
);
}
// --- Main Dashboard ---
export function SpoolBuddyDashboard() {
const { sbState, selectedPrinterId } = useOutletContext();
const { t } = useTranslation();
const { showToast } = useToast();
// Fetch spools for stats, tag lookup, and untagged list
const { data: spools = [], refetch: refetchSpools } = useQuery({
queryKey: ['inventory-spools'],
queryFn: () => api.getSpools(false),
});
// Fetch printers and their statuses for the status badges
const { data: printers = [] } = useQuery({
queryKey: ['printers'],
queryFn: () => api.getPrinters(),
});
const statusQueries = useQueries({
queries: printers.map((printer: Printer) => ({
queryKey: ['printerStatus', printer.id],
queryFn: () => api.getPrinterStatus(printer.id),
refetchInterval: 10000,
select: (data: PrinterStatus) => ({ connected: data?.connected }),
})),
});
// Current Spool card state - persists until user closes or new tag detected
const [displayedTagId, setDisplayedTagId] = useState(null);
const [displayedWeight, setDisplayedWeight] = useState(null);
const [hiddenTagId, setHiddenTagId] = useState(null);
const [showLinkModal, setShowLinkModal] = useState(false);
const [showAssignAmsModal, setShowAssignAmsModal] = useState(false);
const [showQuickAddModal, setShowQuickAddModal] = useState(false);
const [quickAddBusy, setQuickAddBusy] = useState(false);
// Track current tag from state
const currentTagId = sbState.matchedSpool?.tag_uid ?? sbState.unknownTagUid ?? null;
const currentWeight = sbState.weight;
const weightStable = sbState.weightStable;
// Stabilized scale display: only update when change exceeds threshold to prevent bouncing
const stableDisplayWeight = useRef(null);
const WEIGHT_THRESHOLD = 3; // grams - ignore changes smaller than this
if (currentWeight === null) {
stableDisplayWeight.current = null;
} else if (stableDisplayWeight.current === null || Math.abs(currentWeight - stableDisplayWeight.current) >= WEIGHT_THRESHOLD || weightStable) {
stableDisplayWeight.current = currentWeight;
}
const scaleDisplayValue = stableDisplayWeight.current;
// Find spool by tag_id in the loaded spools list
const displayedSpool = useMemo(() => {
if (sbState.matchedSpool?.id) {
const byId = spools.find((s) => s.id === sbState.matchedSpool?.id);
if (byId) return byId;
}
if (!displayedTagId) return null;
return spools.find((s) => tagsEquivalent(s.tag_uid, displayedTagId)) ?? null;
}, [displayedTagId, sbState.matchedSpool, spools]);
// Untagged spools for the Link feature
const untaggedSpools = useMemo(() => {
return spools.filter((s) => !s.tag_uid && !s.archived_at);
}, [spools]);
// Handle tag detection - show card when tag detected, keep until user closes or new tag
useEffect(() => {
if (currentTagId) {
const isHidden = hiddenTagId === currentTagId;
const isDifferentTag = displayedTagId !== null && displayedTagId !== currentTagId;
if (isDifferentTag || (!isHidden && displayedTagId !== currentTagId)) {
setDisplayedTagId(currentTagId);
setDisplayedWeight(null);
setHiddenTagId(null);
}
// Update weight when stable and card is visible
if (!isHidden && currentWeight !== null && weightStable) {
setDisplayedWeight(Math.round(Math.max(0, currentWeight)));
}
} else {
// Tag removed - clear hidden state so same tag can show when re-placed
if (hiddenTagId) {
setDisplayedTagId(null);
setHiddenTagId(null);
setDisplayedWeight(null);
}
}
}, [currentTagId, currentWeight, weightStable, displayedTagId, hiddenTagId]);
// Auto-sync weight once when known spool first detected
const handleCloseSpoolCard = () => {
setHiddenTagId(displayedTagId);
};
const handleLinkTagToSpool = async (spool: InventorySpool) => {
if (!displayedTagId) return;
try {
await api.linkTagToSpool(spool.id, {
tag_uid: displayedTagId,
tag_type: 'generic',
data_origin: 'nfc_link',
});
setShowLinkModal(false);
refetchSpools();
} catch (e) {
console.error('Failed to link tag:', e);
}
};
const handleQuickAddToInventory = async () => {
if (!displayedTagId) return;
setQuickAddBusy(true);
try {
const weight = liveWeight ?? displayedWeight;
await api.createSpool({
material: 'PLA',
subtype: null,
color_name: null,
rgba: null,
brand: null,
label_weight: 1000,
core_weight: 250,
core_weight_catalog_id: null,
weight_used: 0,
slicer_filament: null,
slicer_filament_name: null,
nozzle_temp_min: null,
nozzle_temp_max: null,
note: null,
added_full: null,
last_used: null,
encode_time: null,
tag_uid: displayedTagId,
tray_uuid: null,
data_origin: 'spoolbuddy',
tag_type: 'generic',
cost_per_kg: null,
last_scale_weight: weight !== null ? Math.round(weight) : null,
last_weighed_at: weight !== null ? new Date().toISOString() : null,
});
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error('Failed to quick-add spool:', msg);
showToast(msg || t('spoolbuddy.errors.quickAddFailed', 'Failed to add spool'), 'error');
} finally {
setShowQuickAddModal(false);
setQuickAddBusy(false);
refetchSpools();
}
};
// For unknown tags, use live weight or stored displayed weight
const useScaleWeight = currentWeight !== null &&
(currentTagId === displayedTagId || (currentTagId === null && displayedTagId !== null));
const liveWeight = useScaleWeight ? currentWeight : null;
// Stats
const totalSpools = spools.length;
const materials = new Set(spools.map((s) => s.material)).size;
const brands = new Set(spools.filter((s) => s.brand).map((s) => s.brand)).size;
return (
{/* Compact stats bar */}
{totalSpools}
{t('spoolbuddy.inventory.spools', 'Spools')}
{materials}
{t('spoolbuddy.spool.material', 'Materials')}
{brands}
{t('spoolbuddy.spool.brand', 'Brands')}
{/* Main content: Device (left) + Current Spool (right) */}
{/* Left column */}
{/* Device card */}
{t('spoolbuddy.dashboard.device', 'Device')}
{/* Connection status */}
{sbState.deviceOnline ? t('spoolbuddy.status.online', 'Online') : t('spoolbuddy.status.offline', 'Disconnected')}
{/* Scale weight */}
{t('spoolbuddy.spool.scaleWeight', 'Scale')}
{scaleDisplayValue !== null ? `${Math.abs(scaleDisplayValue) <= 20 ? 0 : Math.round(Math.max(0, scaleDisplayValue))}g` : '\u2014'}
{/* NFC status */}
{currentTagId ? t('spoolbuddy.dashboard.tagDetected', 'Tag detected') : t('spoolbuddy.dashboard.noTag', 'No tag')}
{/* Printer status badges */}
{printers.length > 0 && (
{t('spoolbuddy.dashboard.printers', 'Printers')}
{printers.map((printer: Printer, i: number) => {
const isOnline = statusQueries[i]?.data?.connected ?? false;
return (
);
})}
)}
{/* Right column: Current Spool */}
{t('spoolbuddy.dashboard.currentSpool', 'Current Spool')}
{!sbState.deviceOnline ? (
) : (displayedSpool || sbState.matchedSpool) && displayedTagId && hiddenTagId !== displayedTagId ? (
{
const s = displayedSpool ?? sbState.matchedSpool!;
return {
id: s.id,
tag_uid: displayedTagId,
material: s.material,
subtype: s.subtype,
color_name: s.color_name,
rgba: s.rgba,
brand: s.brand,
label_weight: s.label_weight,
core_weight: s.core_weight,
weight_used: s.weight_used,
};
})()}
scaleWeight={liveWeight ?? displayedWeight}
onSyncWeight={() => refetchSpools()}
onAssignToAms={() => setShowAssignAmsModal(true)}
onClose={handleCloseSpoolCard}
/>
) : currentTagId && displayedTagId && !displayedSpool && !sbState.matchedSpool && hiddenTagId !== displayedTagId ? (
0 ? () => setShowLinkModal(true) : undefined}
onAddToInventory={() => setShowQuickAddModal(true)}
onClose={handleCloseSpoolCard}
/>
) : (
)}
{/* Assign to AMS Modal */}
{displayedSpool && displayedTagId && (
setShowAssignAmsModal(false)}
spool={displayedSpool}
printerId={selectedPrinterId}
/>
)}
{/* Link Tag to Spool Modal */}
{displayedTagId && (
setShowLinkModal(false)}
tagId={displayedTagId}
untaggedSpools={untaggedSpools}
onLink={handleLinkTagToSpool}
/>
)}
{/* Quick-add to Inventory Modal */}
{showQuickAddModal && displayedTagId && (
{t('spoolbuddy.modal.addToInventory', 'Add to Inventory')}
{/* Hint */}
{t('spoolbuddy.modal.quickAddHint', 'For best results, add the spool in the Bambuddy web interface first (with material, color, brand), then use "Link to Spool" here to assign the NFC tag.')}
{t('spoolbuddy.modal.quickAddDesc', 'This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.')}
{displayedTagId}
setShowQuickAddModal(false)}
className="flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]"
>
{t('common.cancel', 'Cancel')}
{quickAddBusy ? t('common.saving', 'Saving...') : t('spoolbuddy.modal.addAnyway', 'Add Anyway')}
)}
);
}