import React, { useState, useMemo } from 'react'; import { ExcelRow, COLUMNS } from '../types'; import { AlertTriangle, CheckCircle2, ChevronDown, ChevronRight, Edit2, Package, Boxes, Scale, Loader2, RefreshCw, Layers, Link2, Search, Filter, X as XIcon, Undo2 } from 'lucide-react'; import { cn } from '../lib/utils'; import { ConfirmModal } from './ConfirmModal'; import { ColumnFilterPopover } from './ColumnFilterPopover'; interface DimensionsViewProps { data: ExcelRow[]; headers: string[]; onEdit: (index: number) => void; onSaveRow: (index: number, updatedRow: ExcelRow) => void; onCaptureState: (message: string) => void; rowStatuses: Record; onRevertRow: (articleNo: string) => void; } interface DimensionGroup { key: string; innerDims: string; rows: { row: ExcelRow; index: number }[]; isInconsistent: boolean; volume: number; discrepancies: { outer: boolean; units: boolean; moq: boolean; }; } interface NearDuplicateCluster { groups: DimensionGroup[]; volumes: number[]; maxDiffPct: number; } export function DimensionsView({ data, headers, onEdit, onSaveRow, onCaptureState, rowStatuses, onRevertRow }: DimensionsViewProps) { const [expandedGroups, setExpandedGroups] = useState>(new Set()); const [expandedNearDuplicates, setExpandedNearDuplicates] = useState>(new Set()); const [showOnlyInconsistent, setShowOnlyInconsistent] = useState(true); const [syncing, setSyncing] = useState<{ key: string, field: string } | null>(null); const [pendingAction, setPendingAction] = useState<{ group: DimensionGroup, sourceRow: ExcelRow, fieldType: 'outer' | 'units' | 'moq' | 'all' } | null>(null); const [clusterSelections, setClusterSelections] = useState>>({}); const [clusterSyncTargets, setClusterSyncTargets] = useState>({}); const [pendingNearDupSync, setPendingNearDupSync] = useState<{ clusterKey: string; targetGroupKey: string; selectedIndices: number[]; } | null>(null); const [search, setSearch] = useState(''); const [lineFilter, setLineFilter] = useState([]); const [classFilter, setClassFilter] = useState([]); const [openFilter, setOpenFilter] = useState<'line' | 'class' | null>(null); const groups = useMemo(() => { const groupMap = new Map(); data.forEach((row, index) => { const iw = String(row[COLUMNS.INNER_W] || '0').trim(); const il = String(row[COLUMNS.INNER_L] || '0').trim(); const ih = String(row[COLUMNS.INNER_H] || '0').trim(); // Normalize key by sorting dimension values so different orderings // (e.g. "29x10x15" vs "10x29x15") are treated as the same group const sortedDims = [parseFloat(il) || 0, parseFloat(iw) || 0, parseFloat(ih) || 0] .sort((a, b) => a - b); const key = sortedDims.join('x'); if (!groupMap.has(key)) { groupMap.set(key, []); } groupMap.get(key)!.push({ row, index }); }); const result: DimensionGroup[] = []; groupMap.forEach((rows, key) => { // Skip empty/placeholder groups (0x0x0 or empty fields) if (key === '0x0x0' || key === 'xx' || key === 'x x') return; const first = rows[0].row; const firstOuter = `${first[COLUMNS.OUTER_L]}x${first[COLUMNS.OUTER_W]}x${first[COLUMNS.OUTER_H]}`; const firstUnits = String(first[COLUMNS.UNITS_OUTER]); const firstMOQ = String(first[COLUMNS.MOQ]); let outerMatch = true; let unitsMatch = true; let moqMatch = true; rows.forEach(({ row }) => { const outer = `${row[COLUMNS.OUTER_L]}x${row[COLUMNS.OUTER_W]}x${row[COLUMNS.OUTER_H]}`; const units = String(row[COLUMNS.UNITS_OUTER]); const moq = String(row[COLUMNS.MOQ]); if (outer !== firstOuter) outerMatch = false; if (units !== firstUnits) unitsMatch = false; if (moq !== firstMOQ) moqMatch = false; }); const parts = key.split('x').map(Number); const volume = parts[0] * parts[1] * parts[2]; result.push({ key, innerDims: key, rows, volume, isInconsistent: !outerMatch || !unitsMatch || !moqMatch, discrepancies: { outer: !outerMatch, units: !unitsMatch, moq: !moqMatch } }); }); return result.sort((a, b) => (b.isInconsistent ? 1 : 0) - (a.isInconsistent ? 1 : 0)); }, [data]); const filteredGroups = useMemo(() => { let result = groups; if (showOnlyInconsistent) { result = result.filter(g => g.isInconsistent || g.rows.some(({ row }) => rowStatuses[String(row[COLUMNS.ARTICLE_NO])] === 'pending') ); } if (search || lineFilter.length > 0 || classFilter.length > 0) { const s = search.toLowerCase(); result = result.filter(g => { const matchesSearch = !search || g.rows.some(({ row }) => String(row[COLUMNS.ARTICLE_NO] || '').toLowerCase().includes(s) || String(row[COLUMNS.ARTICLE_NAME] || '').toLowerCase().includes(s) ); const matchesLine = lineFilter.length === 0 || g.rows.some(({ row }) => lineFilter.includes(String(row[COLUMNS.LINE] || ''))); const matchesClass = classFilter.length === 0 || g.rows.some(({ row }) => classFilter.includes(String(row[COLUMNS.CLASSIFICATION] || ''))); return matchesSearch && matchesLine && matchesClass; }); } return result; }, [groups, showOnlyInconsistent, search, lineFilter, classFilter, rowStatuses]); const uniqueLines = useMemo(() => Array.from(new Set(data.map(r => String(r[COLUMNS.LINE] || '')))).sort() , [data]); const uniqueClasses = useMemo(() => Array.from(new Set(data.map(r => String(r[COLUMNS.CLASSIFICATION] || '')))).sort() , [data]); const nearDuplicateClusters = useMemo((): NearDuplicateCluster[] => { // Two groups are "similar" if every sorted dimension pair differs by < 1 cm absolute // (keys are already sorted ascending, e.g. "15x20x29") const MAX_DIFF_CM = 1; const maxAbsDiff = (keyA: string, keyB: string): number => { const a = keyA.split('x').map(Number); const b = keyB.split('x').map(Number); return Math.max(...a.map((v, i) => Math.abs(v - b[i]))); }; const validGroups = groups.filter(g => g.volume > 0); const assignedKeys = new Set(); const clusters: NearDuplicateCluster[] = []; for (let i = 0; i < validGroups.length; i++) { const a = validGroups[i]; if (assignedKeys.has(a.key)) continue; const cluster: DimensionGroup[] = [a]; assignedKeys.add(a.key); for (let j = i + 1; j < validGroups.length; j++) { const b = validGroups[j]; if (assignedKeys.has(b.key)) continue; // b must be within 1 cm on every axis of every group already in the cluster const isSimilar = cluster.every(g => maxAbsDiff(g.key, b.key) < MAX_DIFF_CM); if (isSimilar) { cluster.push(b); assignedKeys.add(b.key); } } if (cluster.length >= 2) { const volumes = cluster.map(g => g.volume); // Max absolute diff (cm) across all pairs in the cluster let maxDiffPct = 0; for (let x = 0; x < cluster.length; x++) { for (let y = x + 1; y < cluster.length; y++) { maxDiffPct = Math.max(maxDiffPct, maxAbsDiff(cluster[x].key, cluster[y].key)); } } clusters.push({ groups: cluster, volumes, maxDiffPct }); } } return clusters; }, [groups]); const toggleGroup = (key: string) => { const next = new Set(expandedGroups); if (next.has(key)) { next.delete(key); } else { next.add(key); } setExpandedGroups(next); }; const handleSyncField = async (group: DimensionGroup, sourceRow: ExcelRow, fieldType: 'outer' | 'units' | 'moq') => { setPendingAction({ group, sourceRow, fieldType }); }; const handleFullSync = async (group: DimensionGroup, sourceRow: ExcelRow) => { setPendingAction({ group, sourceRow, fieldType: 'all' }); }; const executeNearDupSync = async () => { if (!pendingNearDupSync) return; const { clusterKey, targetGroupKey, selectedIndices } = pendingNearDupSync; const cluster = nearDuplicateClusters.find(c => c.groups[0].key === clusterKey); if (!cluster) return; const targetGroup = cluster.groups.find(g => g.key === targetGroupKey); if (!targetGroup) return; const sourceRow = targetGroup.rows[0].row; const innerL = sourceRow[COLUMNS.INNER_L]; const innerW = sourceRow[COLUMNS.INNER_W]; const innerH = sourceRow[COLUMNS.INNER_H]; onCaptureState(`Synced inner dimensions to ${targetGroupKey} cm for ${selectedIndices.length} products`); setPendingNearDupSync(null); for (const idx of selectedIndices) { const row = data[idx]; const updatedRow = [...row]; updatedRow[COLUMNS.INNER_L] = innerL; updatedRow[COLUMNS.INNER_W] = innerW; updatedRow[COLUMNS.INNER_H] = innerH; await onSaveRow(idx, updatedRow); } setClusterSelections(prev => { const next = { ...prev }; delete next[pendingNearDupSync.clusterKey]; return next; }); }; const executeSync = async () => { if (!pendingAction) return; const { group, sourceRow, fieldType } = pendingAction; const fieldLabel = fieldType === 'outer' ? 'Outer Box Dimensions' : fieldType === 'units' ? 'Units per Outer' : fieldType === 'moq' ? 'MOQ' : 'Full Packaging Data'; onCaptureState(`Bulk synced ${fieldLabel} in group ${group.innerDims}`); setSyncing({ key: group.key, field: fieldType }); setPendingAction(null); try { const outerL = sourceRow[COLUMNS.OUTER_L]; const outerW = sourceRow[COLUMNS.OUTER_W]; const outerH = sourceRow[COLUMNS.OUTER_H]; const unitsOuter = sourceRow[COLUMNS.UNITS_OUTER]; const moq = sourceRow[COLUMNS.MOQ]; for (const { row, index } of group.rows) { if (row === sourceRow) continue; const updatedRow = [...row]; if (fieldType === 'outer') { updatedRow[COLUMNS.OUTER_L] = outerL; updatedRow[COLUMNS.OUTER_W] = outerW; updatedRow[COLUMNS.OUTER_H] = outerH; } else if (fieldType === 'units') { updatedRow[COLUMNS.UNITS_OUTER] = unitsOuter; } else if (fieldType === 'moq') { updatedRow[COLUMNS.MOQ] = moq; } else if (fieldType === 'all') { updatedRow[COLUMNS.OUTER_L] = outerL; updatedRow[COLUMNS.OUTER_W] = outerW; updatedRow[COLUMNS.OUTER_H] = outerH; updatedRow[COLUMNS.UNITS_OUTER] = unitsOuter; updatedRow[COLUMNS.MOQ] = moq; } await onSaveRow(index, updatedRow); } } finally { setSyncing(null); } }; return (
setSearch(e.target.value)} className="w-full pl-9 pr-4 py-2 bg-slate-900 border border-slate-700 rounded-md text-sm text-white focus:outline-none focus:border-blue-500" />
{openFilter === 'line' && ( setLineFilter(prev => prev.includes(val) ? prev.filter(v => v !== val) : [...prev, val])} onSelectAll={setLineFilter} onClear={() => setLineFilter([])} onClose={() => setOpenFilter(null)} title="Filter by Line" className="left-auto right-0" /> )}
{openFilter === 'class' && ( setClassFilter(prev => prev.includes(val) ? prev.filter(v => v !== val) : [...prev, val])} onSelectAll={setClassFilter} onClear={() => setClassFilter([])} onClose={() => setOpenFilter(null)} title="Filter by Classification" className="left-auto right-0" /> )}
{(lineFilter.length > 0 || classFilter.length > 0 || search) && ( )}
{groups.filter(g => g.isInconsistent).length} ISSUES
{nearDuplicateClusters.length > 0 && (
Possible data entry errors {nearDuplicateClusters.length} cluster{nearDuplicateClusters.length !== 1 ? 's' : ''} with dimensions differing <1 cm per axis
{nearDuplicateClusters.map((cluster, ci) => { const allClusterRows = cluster.groups.flatMap(g => g.rows); const clusterKey = cluster.groups[0].key; const selection = clusterSelections[clusterKey] ?? new Set(); const targetKey = clusterSyncTargets[clusterKey] ?? cluster.groups[0].key; return (
{expandedNearDuplicates.has(ci) && (
Sync selected to: {selection.size > 0 && ( )}
{allClusterRows.map(({ row, index }) => { const isSelected = selection.has(index); return (
setClusterSelections(prev => { const current = new Set(prev[clusterKey] ?? []); if (current.has(index)) current.delete(index); else current.add(index); return { ...prev, [clusterKey]: current }; })} >
{row[COLUMNS.ARTICLE_NO]} {row[COLUMNS.ARTICLE_NAME]}
{row[COLUMNS.INNER_L]} × {row[COLUMNS.INNER_W]} × {row[COLUMNS.INNER_H]} cm
); })}
)}
); })}
)}
{filteredGroups.map(group => { const hasPending = group.rows.some(({ row }) => rowStatuses[String(row[COLUMNS.ARTICLE_NO])] === 'pending'); return (
{group.discrepancies.outer && ( Outer Dims vary )} {group.discrepancies.units && ( Units/Outer vary )} {group.discrepancies.moq && ( MOQ varies )}
{group.isInconsistent && !expandedGroups.has(group.key) && (
OPEN TO SYNC FIELDS
)}
{expandedGroups.has(group.key) && (
{group.rows.map(({ row, index }) => { const isPending = rowStatuses[String(row[COLUMNS.ARTICLE_NO])] === 'pending'; return ( ); })}
Article No / Name Inner Box (L/W/H) Outer Box (L/W/H) Units/Outer MOQ Actions
{row[COLUMNS.ARTICLE_NO]}
{row[COLUMNS.ARTICLE_NAME]}
{row[COLUMNS.INNER_L] || '-'} × {row[COLUMNS.INNER_W] || '-'} × {row[COLUMNS.INNER_H] || '-'}
{row[COLUMNS.OUTER_L] || '-'} × {row[COLUMNS.OUTER_W] || '-'} × {row[COLUMNS.OUTER_H] || '-'}
{row[COLUMNS.UNITS_OUTER] || '-'}
{row[COLUMNS.MOQ] || '-'}
)}
); })} {filteredGroups.length === 0 && (

Clear of discrepancies

{showOnlyInconsistent ? "No inconsistent groups found." : "No dimension data available."}

)}
setPendingAction(null)} title="Sync Group Data" message={`Are you sure you want to sync ${pendingAction?.fieldType === 'all' ? 'ALL packaging data' : pendingAction?.fieldType} for the whole group using product ${pendingAction?.sourceRow[COLUMNS.ARTICLE_NO]} as the template?`} type="warning" confirmText="Sync Group" /> setPendingNearDupSync(null)} title="Sync Inner Dimensions" message={`Update inner dimensions to ${pendingNearDupSync?.targetGroupKey} cm for ${pendingNearDupSync?.selectedIndices.length} selected product${(pendingNearDupSync?.selectedIndices.length ?? 0) !== 1 ? 's' : ''}?`} type="warning" confirmText="Sync Dimensions" />
); }