import { useState, useMemo } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { X, Loader2, Search, Link } from 'lucide-react'; import { api } from '../api/client'; import type { InventorySpool } from '../api/client'; import { Button } from './Button'; import { useToast } from '../contexts/ToastContext'; interface LinkSpoolModalProps { isOpen: boolean; onClose: () => void; tagUid: string; trayUuid: string; printerId: number; amsId: number; trayId: number; } export function LinkSpoolModal({ isOpen, onClose, tagUid, trayUuid, printerId, amsId, trayId }: LinkSpoolModalProps) { const { t } = useTranslation(); const queryClient = useQueryClient(); const { showToast } = useToast(); const [search, setSearch] = useState(''); const { data: spools, isLoading } = useQuery({ queryKey: ['inventory-spools'], queryFn: () => api.getSpools(false), enabled: isOpen, }); // Filter to untagged spools matching search const filteredSpools = useMemo(() => { if (!spools) return []; return spools.filter((s: InventorySpool) => { if (s.tag_uid || s.tray_uuid) return false; // Already tagged if (!search) return true; const q = search.toLowerCase(); return ( s.material.toLowerCase().includes(q) || (s.brand && s.brand.toLowerCase().includes(q)) || (s.color_name && s.color_name.toLowerCase().includes(q)) ); }); }, [spools, search]); const linkMutation = useMutation({ mutationFn: (spoolId: number) => api.linkTagToSpool(spoolId, { tag_uid: tagUid || undefined, tray_uuid: trayUuid || undefined, tag_type: trayUuid ? 'bambulab' : 'generic', data_origin: 'nfc_link', }), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['inventory-spools'] }); queryClient.invalidateQueries({ queryKey: ['inventory-assignments'] }); showToast(t('inventory.tagLinked'), 'success'); onClose(); }, onError: (err: Error) => { showToast(err.message || t('inventory.tagLinkFailed'), 'error'); }, }); if (!isOpen) return null; return (
{/* Header */}

{t('inventory.linkToSpool')}

AMS {amsId} T{trayId} · Printer #{printerId}

{/* Search */}
setSearch(e.target.value)} placeholder={t('inventory.searchSpools')} className="w-full pl-9 pr-3 py-2 bg-bambu-dark rounded-lg border border-white/10 text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green" />
{(tagUid || trayUuid) && (

Tag: {tagUid || trayUuid}

)}
{/* Spool List */}
{isLoading ? (
) : filteredSpools.length === 0 ? (

{t('inventory.noSpoolsMatch')}

) : ( filteredSpools.map((spool: InventorySpool) => ( )) )}
{/* Footer */}
); }