import { useState, useMemo, type ReactNode } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { Plus, Loader2, Trash2, Archive, RotateCcw, Edit2, Package, Search, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight, TrendingDown, Layers, Printer, AlertTriangle, X, Clock, LayoutGrid, TableProperties, Columns, } from 'lucide-react'; import { api } from '../api/client'; import type { InventorySpool, SpoolAssignment } from '../api/client'; import { Button } from '../components/Button'; import { SpoolFormModal } from '../components/SpoolFormModal'; import { ColumnConfigModal, type ColumnConfig } from '../components/ColumnConfigModal'; import { useToast } from '../contexts/ToastContext'; type ArchiveFilter = 'active' | 'archived'; type UsageFilter = 'all' | 'used' | 'new'; type ViewMode = 'table' | 'cards'; // Column definitions for the inventory table const COLUMN_CONFIG_KEY = 'bambuddy-inventory-columns'; const DEFAULT_COLUMNS: ColumnConfig[] = [ { id: 'id', label: '#', visible: true }, { id: 'added_time', label: 'Added', visible: true }, { id: 'encode_time', label: 'Encoded', visible: false }, { id: 'last_used_time', label: 'Last Used', visible: false }, { id: 'rgba', label: 'Color', visible: true }, { id: 'material', label: 'Material', visible: true }, { id: 'subtype', label: 'Subtype', visible: true }, { id: 'color_name', label: 'Color Name', visible: false }, { id: 'brand', label: 'Brand', visible: true }, { id: 'slicer_filament', label: 'Slicer Filament', visible: false }, { id: 'location', label: 'Location', visible: true }, { id: 'label_weight', label: 'Label', visible: true }, { id: 'net', label: 'Net', visible: true }, { id: 'gross', label: 'Gross', visible: false }, { id: 'added_full', label: 'Full', visible: false }, { id: 'used', label: 'Used', visible: false }, { id: 'printed_total', label: 'Printed Total', visible: false }, { id: 'printed_since_weight', label: 'Printed Since Weight', visible: false }, { id: 'note', label: 'Note', visible: false }, { id: 'pa_k', label: 'PA(K)', visible: true }, { id: 'tag_id', label: 'Tag ID', visible: false }, { id: 'data_origin', label: 'Data Origin', visible: false }, { id: 'tag_type', label: 'Linked Tag Type', visible: false }, { id: 'remaining', label: 'Remaining', visible: true }, ]; function loadColumnConfig(): ColumnConfig[] { try { const stored = localStorage.getItem(COLUMN_CONFIG_KEY); if (stored) { const parsed = JSON.parse(stored) as ColumnConfig[]; const defaultIds = new Set(DEFAULT_COLUMNS.map((c) => c.id)); const storedIds = new Set(parsed.map((c) => c.id)); // Keep stored columns that still exist in defaults const validStored = parsed.filter((c) => defaultIds.has(c.id)); // Add any new default columns not in stored config const newColumns = DEFAULT_COLUMNS.filter((c) => !storedIds.has(c.id)); return [...validStored, ...newColumns]; } } catch { // Ignore errors } return DEFAULT_COLUMNS.map((c) => ({ ...c })); } function saveColumnConfig(config: ColumnConfig[]) { try { localStorage.setItem(COLUMN_CONFIG_KEY, JSON.stringify(config)); } catch { // Ignore errors } } function formatWeight(g: number, useKg = false): string { if (useKg && g >= 1000) return `${(g / 1000).toFixed(1)}kg`; return `${Math.round(g)}g`; } // Material color mapping for pills const MATERIAL_COLORS: Record = { PLA: 'bg-green-500/20 text-green-400', ABS: 'bg-red-500/20 text-red-400', PETG: 'bg-blue-500/20 text-blue-400', TPU: 'bg-purple-500/20 text-purple-400', ASA: 'bg-orange-500/20 text-orange-400', PA: 'bg-yellow-500/20 text-yellow-400', PC: 'bg-cyan-500/20 text-cyan-400', PET: 'bg-sky-500/20 text-sky-400', }; type TFn = (key: string) => string; function formatDate(dateStr: string | null): string { if (!dateStr) return '-'; const date = new Date(dateStr); return date.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: '2-digit' }); } type CellCtx = { spool: InventorySpool; remaining: number; pct: number; assignmentMap: Record; }; // Column header labels (25 columns — matching SpoolBuddy exactly) const columnHeaders: Record string> = { id: () => '#', added_time: () => 'Added', encode_time: () => 'Encoded', last_used_time: () => 'Last Used', rgba: (t) => t('inventory.color'), material: (t) => t('inventory.material'), subtype: (t) => t('inventory.subtype'), color_name: (t) => t('inventory.colorName'), brand: (t) => t('inventory.brand'), slicer_filament: (t) => t('inventory.slicerFilament'), location: () => 'Location', label_weight: (t) => t('inventory.labelWeight'), net: (t) => t('inventory.net'), gross: () => 'Gross', added_full: () => 'Full', used: (t) => t('inventory.weightUsed'), printed_total: () => 'Printed Total', printed_since_weight: () => 'Printed Since Weight', note: (t) => t('inventory.note'), pa_k: () => 'PA(K)', tag_id: () => 'Tag ID', data_origin: () => 'Data Origin', tag_type: () => 'Linked Tag Type', remaining: (t) => t('inventory.remaining'), }; // Column cell renderers (25 columns — matching SpoolBuddy exactly) const columnCells: Record ReactNode> = { id: ({ spool }) => ( {spool.id} ), added_time: ({ spool }) => ( {formatDate(spool.created_at)} ), encode_time: ({ spool }) => ( {formatDate(spool.encode_time)} ), last_used_time: ({ spool }) => ( {spool.last_used ? formatDate(spool.last_used) : 'Never'} ), rgba: ({ spool }) => (
{spool.color_name || '-'}
), material: ({ spool }) => ( {spool.material} ), subtype: ({ spool }) => ( {spool.subtype || '-'} ), color_name: ({ spool }) => ( {spool.color_name || '-'} ), brand: ({ spool }) => ( {spool.brand || '-'} ), slicer_filament: ({ spool }) => ( {spool.slicer_filament_name || spool.slicer_filament || '-'} ), location: ({ spool, assignmentMap }) => { const assignment = assignmentMap[spool.id]; if (!assignment) return -; return ( AMS {assignment.ams_id} T{assignment.tray_id} ); }, label_weight: ({ spool }) => ( {formatWeight(spool.label_weight)} ), net: ({ remaining }) => ( {formatWeight(remaining)} ), gross: ({ spool, remaining }) => ( {formatWeight(remaining + spool.core_weight)} ), added_full: ({ spool }) => ( {spool.added_full == null ? '-' : spool.added_full ? 'Yes' : 'No'} ), used: ({ spool }) => ( {spool.weight_used > 0 ? formatWeight(spool.weight_used) : '-'} ), printed_total: () => ( - ), printed_since_weight: () => ( - ), note: ({ spool }) => ( {spool.note || '-'} ), pa_k: ({ spool }) => { const count = spool.k_profiles?.length ?? 0; if (count === 0) return -; return ( K ); }, tag_id: ({ spool }) => { const tag = spool.tag_uid || spool.tray_uuid; if (!tag) return -; return ( {tag.length > 12 ? `${tag.slice(0, 6)}...${tag.slice(-4)}` : tag} ); }, data_origin: ({ spool }) => ( {spool.data_origin || '-'} ), tag_type: ({ spool }) => ( {spool.tag_type || '-'} ), remaining: ({ remaining, pct }) => (
50 ? 'bg-bambu-green' : pct > 20 ? 'bg-yellow-500' : 'bg-red-500'}`} style={{ width: `${Math.min(pct, 100)}%` }} />
{Math.round(remaining)}g
), }; export default function InventoryPage() { const { t } = useTranslation(); const queryClient = useQueryClient(); const { showToast } = useToast(); const [formModal, setFormModal] = useState<{ spool?: InventorySpool | null } | null>(null); // Filter state const [archiveFilter, setArchiveFilter] = useState('active'); const [usageFilter, setUsageFilter] = useState('all'); const [materialFilter, setMaterialFilter] = useState(''); const [brandFilter, setBrandFilter] = useState(''); const [search, setSearch] = useState(''); const [viewMode, setViewMode] = useState('table'); const [columnConfig, setColumnConfig] = useState(loadColumnConfig); const [showColumnModal, setShowColumnModal] = useState(false); // Pagination state const [pageIndex, setPageIndex] = useState(0); const [pageSize, setPageSize] = useState(15); const { data: spools, isLoading } = useQuery({ queryKey: ['inventory-spools'], queryFn: () => api.getSpools(true), // Always fetch all, filter client-side }); const { data: assignments } = useQuery({ queryKey: ['spool-assignments'], queryFn: () => api.getAssignments(), }); const deleteMutation = useMutation({ mutationFn: (id: number) => api.deleteSpool(id), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['inventory-spools'] }); showToast(t('inventory.spoolDeleted'), 'success'); }, }); const archiveMutation = useMutation({ mutationFn: (id: number) => api.archiveSpool(id), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['inventory-spools'] }); showToast(t('inventory.spoolArchived'), 'success'); }, }); const restoreMutation = useMutation({ mutationFn: (id: number) => api.restoreSpool(id), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['inventory-spools'] }); showToast(t('inventory.spoolRestored'), 'success'); }, }); // Stats calculation (active spools only) const stats = useMemo(() => { if (!spools) return null; let totalWeight = 0; let totalConsumed = 0; let lowStock = 0; let activeCount = 0; const byMaterial: Record = {}; for (const s of spools) { if (s.archived_at) continue; activeCount++; const remaining = Math.max(0, s.label_weight - s.weight_used); totalWeight += remaining; totalConsumed += s.weight_used; const pct = s.label_weight > 0 ? (remaining / s.label_weight) * 100 : 0; if (pct < 20) lowStock++; const mat = s.material || 'Unknown'; if (!byMaterial[mat]) byMaterial[mat] = { count: 0, weight: 0 }; byMaterial[mat].count++; byMaterial[mat].weight += remaining; } return { totalWeight, totalConsumed, lowStock, byMaterial, totalSpools: activeCount }; }, [spools]); const inPrinterCount = assignments?.length ?? 0; // Map spool_id -> assignment for location column const assignmentMap = useMemo(() => { const map: Record = {}; for (const a of assignments || []) { map[a.spool_id] = a; } return map; }, [assignments]); // Top materials by weight for stat card pills const topMaterials = useMemo(() => { if (!stats) return []; return Object.entries(stats.byMaterial) .sort((a, b) => b[1].weight - a[1].weight) .slice(0, 4); }, [stats]); // Filtering pipeline const filteredSpools = useMemo(() => { let filtered = spools || []; // Archive filter if (archiveFilter === 'active') { filtered = filtered.filter((s) => !s.archived_at); } else { filtered = filtered.filter((s) => !!s.archived_at); } // Usage filter if (usageFilter === 'used') { filtered = filtered.filter((s) => s.weight_used > 0); } else if (usageFilter === 'new') { filtered = filtered.filter((s) => s.weight_used === 0); } // Material dropdown if (materialFilter) { filtered = filtered.filter((s) => s.material === materialFilter); } // Brand dropdown if (brandFilter) { filtered = filtered.filter((s) => s.brand === brandFilter); } // Global search if (search) { const q = search.toLowerCase(); filtered = filtered.filter((s) => s.brand?.toLowerCase().includes(q) || s.material.toLowerCase().includes(q) || s.color_name?.toLowerCase().includes(q) || s.subtype?.toLowerCase().includes(q) || s.note?.toLowerCase().includes(q) || s.slicer_filament_name?.toLowerCase().includes(q) ); } return filtered; }, [spools, archiveFilter, usageFilter, materialFilter, brandFilter, search]); // Pagination const totalPages = Math.max(1, Math.ceil(filteredSpools.length / pageSize)); const safePageIndex = Math.min(pageIndex, totalPages - 1); const pagedSpools = filteredSpools.slice(safePageIndex * pageSize, (safePageIndex + 1) * pageSize); // Reset page on filter changes const resetPage = () => setPageIndex(0); // Unique values for filter dropdowns const uniqueMaterials = [...new Set(spools?.map((s) => s.material) || [])].sort(); const uniqueBrands = [...new Set(spools?.map((s) => s.brand).filter(Boolean) || [])].sort() as string[]; // Check if any filters are non-default const hasActiveFilters = archiveFilter !== 'active' || usageFilter !== 'all' || !!materialFilter || !!brandFilter || !!search; const handleColumnConfigSave = (config: ColumnConfig[]) => { setColumnConfig(config); saveColumnConfig(config); }; // Visible column IDs in order const visibleColumns = useMemo( () => columnConfig.filter((c) => c.visible).map((c) => c.id), [columnConfig] ); const clearAllFilters = () => { setArchiveFilter('active'); setUsageFilter('all'); setMaterialFilter(''); setBrandFilter(''); setSearch(''); resetPage(); }; return (
{/* Header */}

{t('inventory.title')}

{t('inventory.noSpools').split('.')[0] ? '' : ''}

{/* Stats Bar */} {stats && !isLoading && (
{/* Total Inventory */}
{t('inventory.totalInventory')}
{formatWeight(stats.totalWeight, true)}
{stats.totalSpools} {stats.totalSpools !== 1 ? t('inventory.spools') : t('inventory.spool')}
{/* Total Consumed */}
{t('inventory.totalConsumed')}
{formatWeight(stats.totalConsumed, true)}
{t('inventory.sinceTracking')}
{/* By Material */}
{t('inventory.byMaterial')}
{topMaterials.map(([mat, data]) => ( {mat} {formatWeight(data.weight, true)} ))}
{/* In Printer */}
{t('inventory.inPrinter')}
{inPrinterCount}
{t('inventory.loadedInAms')}
{/* Low Stock */}
{t('inventory.lowStock')}
0 ? 'text-yellow-400' : 'text-white'}`}>{stats.lowStock}
{t('inventory.lowStockThreshold')}
)} {/* Toolbar: Search + View toggle */}
{ setSearch(e.target.value); resetPage(); }} placeholder={t('inventory.search')} className="w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green" /> {search && ( )}
{/* Columns button */} {/* Table / Cards toggle */}
{/* Filter chips row */}
{/* Active / Archived chips */}
{/* All / Used / New chips */}
{/* Material dropdown chip */} {/* Brand dropdown chip */} {/* Clear filters */} {hasActiveFilters && ( <>
)} {/* Results count */} {filteredSpools.length} {filteredSpools.length !== 1 ? t('inventory.spools') : t('inventory.spool')}
{/* Content */} {isLoading ? (
) : viewMode === 'cards' ? ( /* Cards view */ pagedSpools.length > 0 ? ( <>
{pagedSpools.map((spool) => { const remaining = Math.max(0, spool.label_weight - spool.weight_used); const pct = spool.label_weight > 0 ? (remaining / spool.label_weight) * 100 : 0; const colorStyle = spool.rgba ? `#${spool.rgba.substring(0, 6)}` : '#808080'; return (
setFormModal({ spool })} > {/* Color header */}
{spool.color_name || '-'}
{/* Content */}

{spool.material}{spool.subtype ? ` ${spool.subtype}` : ''}

{spool.brand || '-'}

#{spool.id}
{/* Progress */}
{t('inventory.remaining')} {Math.round(pct)}%
50 ? 'bg-bambu-green' : pct > 20 ? 'bg-yellow-500' : 'bg-red-500'}`} style={{ width: `${Math.min(pct, 100)}%` }} />
{Math.round(remaining)}g
{/* Weight info */}
{t('inventory.labelWeight')}: {formatWeight(spool.label_weight)}
{t('inventory.weightUsed')}: {spool.weight_used > 0 ? formatWeight(spool.weight_used) : '-'}
{/* Note */} {spool.note && (
{spool.note}
)}
); })}
{/* Pagination for cards */} { setPageSize(size); resetPage(); }} t={t} /> ) : ( setFormModal({ spool: null })} t={t} /> ) ) : ( /* Table view */ pagedSpools.length > 0 ? (
{visibleColumns.map((colId) => ( ))} {pagedSpools.map((spool) => { const remaining = Math.max(0, spool.label_weight - spool.weight_used); const pct = spool.label_weight > 0 ? (remaining / spool.label_weight) * 100 : 0; return ( setFormModal({ spool })} > {visibleColumns.map((colId) => ( ))} ); })}
{columnHeaders[colId]?.(t) ?? colId} {t('common.actions')}
{columnCells[colId]?.({ spool, remaining, pct, assignmentMap })}
e.stopPropagation()}> {spool.archived_at ? ( ) : ( )}
{/* Pagination inside card footer */}
{t('inventory.showing')} {safePageIndex * pageSize + 1} {t('inventory.to')}{' '} {Math.min((safePageIndex + 1) * pageSize, filteredSpools.length)}{' '} {t('inventory.of')} {filteredSpools.length} {t('inventory.spools')}
{t('inventory.show')} {t('inventory.page')} {safePageIndex + 1} {t('inventory.of')} {totalPages}
) : ( setFormModal({ spool: null })} t={t} /> ) )} {/* Spool Form Modal */} {formModal !== null && ( setFormModal(null)} spool={formModal.spool} /> )} {/* Column Config Modal */} setShowColumnModal(false)} columns={columnConfig} defaultColumns={DEFAULT_COLUMNS} onSave={handleColumnConfigSave} />
); } /* Pagination bar (reused for cards view) */ function PaginationBar({ pageIndex, pageSize, totalRows, totalPages, onPageChange, onPageSizeChange, t, }: { pageIndex: number; pageSize: number; totalRows: number; totalPages: number; onPageChange: (page: number) => void; onPageSizeChange: (size: number) => void; t: (key: string) => string; }) { if (totalPages <= 1) return null; return (
{t('inventory.showing')} {pageIndex * pageSize + 1} {t('inventory.to')}{' '} {Math.min((pageIndex + 1) * pageSize, totalRows)}{' '} {t('inventory.of')} {totalRows} {t('inventory.spools')}
{t('inventory.show')} {t('inventory.page')} {pageIndex + 1} {t('inventory.of')} {totalPages}
); } /* Empty state matching SpoolBuddy's design */ function EmptyFilterState({ hasFilters, onAddSpool, t, }: { hasFilters: boolean; onAddSpool: () => void; t: (key: string) => string; }) { return (
{hasFilters ? ( ) : (
+
)}

{hasFilters ? t('inventory.noSpoolsMatch') : t('inventory.noSpools').split('.')[0]}

{hasFilters ? t('inventory.noSpoolsMatchDesc') : t('inventory.noSpools') }

{!hasFilters && ( )}
); }