import { useState, useMemo } from 'react'; import { Dialog, DialogContent, DialogHeader, DialogTitle, } from '@/Components/ui/dialog'; import { Input } from '@/Components/ui/input'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@/Components/ui/table'; import { Badge } from '@/Components/ui/badge'; import { Package, Search } from 'lucide-react'; interface MaterialOption { id: number; ulid: string; name: string; sku?: string; unit: string; unit_cost: string; category?: string; } interface MaterialBrowserModalProps { open: boolean; onOpenChange: (open: boolean) => void; title?: string; materials: MaterialOption[]; } const formatCurrency = (v: string) => new Intl.NumberFormat('en-PH', { style: 'currency', currency: 'PHP' }).format(Number(v)); type SortKey = 'name' | 'sku' | 'category' | 'unit' | 'unit_cost'; type SortDir = 'asc' | 'desc'; export default function MaterialBrowserModal({ open, onOpenChange, title = 'Materials', materials, }: MaterialBrowserModalProps) { const [search, setSearch] = useState(''); const [sortKey, setSortKey] = useState('name'); const [sortDir, setSortDir] = useState('asc'); const handleSort = (key: SortKey) => { if (sortKey === key) { setSortDir(sortDir === 'asc' ? 'desc' : 'asc'); } else { setSortKey(key); setSortDir('asc'); } }; const sortIndicator = (key: SortKey) => { if (sortKey !== key) return null; return {sortDir === 'asc' ? '↑' : '↓'}; }; const filtered = useMemo(() => { const q = search.toLowerCase().trim(); let list = materials; if (q) { list = list.filter( (m) => m.name.toLowerCase().includes(q) || (m.sku && m.sku.toLowerCase().includes(q)) || (m.category && m.category.toLowerCase().includes(q)) ); } return [...list].sort((a, b) => { const aVal = (a[sortKey] ?? '').toString().toLowerCase(); const bVal = (b[sortKey] ?? '').toString().toLowerCase(); if (sortKey === 'unit_cost') { const diff = Number(a.unit_cost) - Number(b.unit_cost); return sortDir === 'asc' ? diff : -diff; } const cmp = aVal.localeCompare(bVal); return sortDir === 'asc' ? cmp : -cmp; }); }, [materials, search, sortKey, sortDir]); return ( {title} {materials.length}
setSearch(e.target.value)} className="pl-10" />
{filtered.length === 0 ? (

{search ? 'No materials match your search.' : 'No materials in this group.'}

) : ( handleSort('name')} > Material {sortIndicator('name')} handleSort('sku')} > SKU {sortIndicator('sku')} handleSort('category')} > Category {sortIndicator('category')} handleSort('unit')} > Unit {sortIndicator('unit')} handleSort('unit_cost')} > Unit Cost {sortIndicator('unit_cost')} {filtered.map((m) => ( {m.name} {m.sku || '-'} {m.category || '-'} {m.unit} {formatCurrency(m.unit_cost)} ))}
)}
{filtered.length > 0 && filtered.length !== materials.length && (

Showing {filtered.length} of {materials.length} materials

)}
); }