/** * @license * SPDX-License-Identifier: Apache-2.0 */ import React, { useState, useMemo } from 'react'; import { motion, AnimatePresence } from 'motion/react'; import { Package, Plus, History, Trash2, Edit, Folder, AlertTriangle, ChevronRight, ArrowUpRight, ArrowDownRight, Search, Filter, Check, PlusCircle, TrendingUp, Sliders, DollarSign, Tag } from 'lucide-react'; import { TireProduct, StockHistoryItem, StaffUser, SystemSettings } from '../types'; interface InventoryManagerProps { products: TireProduct[]; history: StockHistoryItem[]; currentStaff: StaffUser; settings: SystemSettings; onAdjustProductStock: (productId: string, quantityChange: number, type: StockHistoryItem['type'], reason: string) => void; onAddNewProduct: (product: TireProduct) => void; onDeleteProduct: (productId: string) => void; } export default function InventoryManager({ products, history, currentStaff, settings, onAdjustProductStock, onAddNewProduct, onDeleteProduct }: InventoryManagerProps) { const [selectedProduct, setSelectedProduct] = useState(null); const [inventorySearch, setInventorySearch] = useState(''); const [activeSegment, setActiveSegment] = useState('All'); // Custom New Product Addition Modal toggle const [showAddModal, setShowAddModal] = useState(false); // Manual Adjustment flow inside details const [adjustmentQty, setAdjustmentQty] = useState(5); const [adjustmentType, setAdjustmentType] = useState<'STOCK_IN' | 'STOCK_OUT' | 'MANUAL_ADJUSTMENT'>('STOCK_IN'); const [adjustmentReason, setAdjustmentReason] = useState(''); // New Product details state const [newBrand, setNewBrand] = useState(''); const [newModel, setNewModel] = useState(''); const [newSize, setNewSize] = useState(''); const [newCategory, setNewCategory] = useState('Passenger'); const [newPrice, setNewPrice] = useState(15000); const [newPurchasePrice, setNewPurchasePrice] = useState(11000); const [newStock, setNewStock] = useState(10); const [newMinStock, setNewMinStock] = useState(5); const [newSku, setNewSku] = useState(''); const [newDesc, setNewDesc] = useState(''); // 1. Filtering products const filteredProducts = useMemo(() => { return products.filter(p => { const matchSearch = p.brand.toLowerCase().includes(inventorySearch.toLowerCase()) || p.model.toLowerCase().includes(inventorySearch.toLowerCase()) || p.size.toLowerCase().includes(inventorySearch.toLowerCase()) || p.sku.toLowerCase().includes(inventorySearch.toLowerCase()); const matchSegment = activeSegment === 'All' || p.category === activeSegment; return matchSearch && matchSegment; }); }, [products, inventorySearch, activeSegment]); // If a product is selected, pull its dedicated history records const selectedProductHistory = useMemo(() => { if (!selectedProduct) return []; return history .filter(h => h.productId === selectedProduct.id) .sort((a, b) => new Date(b.dateTime).getTime() - new Date(a.dateTime).getTime()); }, [history, selectedProduct]); // Stock valuation and item counts const totalSkuInSegment = filteredProducts.length; const totalCountInSegment = filteredProducts.reduce((sum, p) => sum + p.stock, 0); const totalValuationInSegment = filteredProducts.reduce((sum, p) => sum + (p.stock * p.price), 0); const totalCostValuation = filteredProducts.reduce((sum, p) => sum + (p.stock * p.purchasePrice), 0); const projectedMargin = totalValuationInSegment - totalCostValuation; // Handle Adjustment submission const handleAdjustmentSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!selectedProduct) return; if (adjustmentQty <= 0) { alert("Adjustment quantity must be greater than zero."); return; } if (!adjustmentReason.trim()) { alert("Please state concrete audit adjustment comments."); return; } // Determine quantity with correct algebraic sign: STOCK_IN (+), OUT/MAN ADJUSTMENT (-) let finalQtyChange = adjustmentQty; if (adjustmentType === 'STOCK_OUT') { finalQtyChange = -adjustmentQty; } else if (adjustmentType === 'MANUAL_ADJUSTMENT') { // Manual adjustment could be adding or subtracting // In our code logic, we'll let manager define positive adjustments as + adjustmentQty // But we can let them input negative values or specify direct relative overrides! // Here let's treat manual adjustment as relative addition. Let's ask them to input signed or we define. // Let's assume standard manual addition. If they want to decrease, they select "Stock Out". finalQtyChange = adjustmentQty; } // Guard stock limit if (adjustmentType === 'STOCK_OUT' && selectedProduct.stock + finalQtyChange < 0) { alert("Cannot complete operation! Net inventory stock cannot go below 0."); return; } onAdjustProductStock( selectedProduct.id, finalQtyChange, adjustmentType, adjustmentReason.trim() ); // Sync selected item card visual indicators const updatedProd = products.find(p => p.id === selectedProduct.id); if (updatedProd) { setSelectedProduct({ ...updatedProd, stock: updatedProd.stock + finalQtyChange }); } // Reset forms setAdjustmentQty(5); setAdjustmentReason(''); setAdjustmentType('STOCK_IN'); }; // Create Product Submit const handleCreateProductSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!newBrand.trim() || !newModel.trim() || !newSize.trim() || !newSku.trim()) { alert("Brand, Model, Size and SKU are mandatory properties."); return; } // SKU uniqueness guard if (products.some(p => p.sku.toUpperCase() === newSku.toUpperCase())) { alert("SKU already active under another tire spec. Assign unique tracking barcode."); return; } const newProd: TireProduct = { id: 'p_' + Math.random().toString(36).substr(2, 9), sku: newSku.toUpperCase(), brand: newBrand, model: newModel, size: newSize, category: newCategory, stock: newStock, minStock: newMinStock, price: newPrice, purchasePrice: newPurchasePrice, description: newDesc.trim() || undefined }; onAddNewProduct(newProd); // Reset states setNewBrand(''); setNewModel(''); setNewSize(''); setNewSku(''); setNewDesc(''); setNewStock(10); setNewMinStock(5); setNewPrice(15000); setNewPurchasePrice(11000); setShowAddModal(false); }; const handleProductDelete = (productId: string) => { if (confirm("Are you absolutely sure you want to retire and remove this tire product spec? Historical invoice records will still show details, but stock adjustments will be closed.")) { onDeleteProduct(productId); if (selectedProduct?.id === productId) { setSelectedProduct(null); } } }; return (
{/* Category Summaries & Valuation overview cards */}
Active Segment SKUs

{totalSkuInSegment} Profiles

Currently filtered category

Physical Tires Inventory

{totalCountInSegment} units

Physical tire units stored

Estimated Retail Value

{settings.currencySymbol} {totalValuationInSegment.toLocaleString()}

Total potential turnover value

Projected Profit Margin

{settings.currencySymbol} {projectedMargin.toLocaleString()}

Est. average margin: {Math.round((projectedMargin / (totalValuationInSegment || 1)) * 100)}%

{/* LEFT COLUMN: Core product list table */}

Haider Tire Warehouse Records

Configure stocks details, track low alerts, and view specific SKU histories

{['owner', 'manager'].includes(currentStaff.role) && ( )}
{/* Filtering row */}
{/* Search */}
setInventorySearch(e.target.value)} className="w-full text-xs border border-slate-200 outline-none focus:border-slate-800 bg-white hover:bg-slate-50/50 focus:bg-white rounded-lg pl-10 pr-4 py-2.5 transition" />
{/* Filter segments tab */}
{['All', 'Passenger', 'SUV', 'Commercial', 'Light Truck', 'Truck/Bus'].map(seg => ( ))}
{/* Core Table Grid layout */}
{filteredProducts.length === 0 ? ( ) : ( filteredProducts.map((p) => { const isLow = p.stock <= p.minStock; const isSelected = selectedProduct?.id === p.id; return ( setSelectedProduct(p)} > ); }) )}
SKU / Tire Name Category Remaining Cost Price Sell Price Audit Actions
No products matched current filters or search query.
{p.brand} {p.model} {isLow && ( ALERT )}
{p.size} SKU: {p.sku}
{p.category} {p.stock} {settings.currencySymbol} {p.purchasePrice.toLocaleString()} {settings.currencySymbol} {p.price.toLocaleString()}
e.stopPropagation()}> {['owner', 'manager'].includes(currentStaff.role) && ( )}
{/* RIGHT COLUMN: Selective detailed histories & manual stock operations drawer */} {selectedProduct && (
{/* Product Header Card */}
Detailed Tire Portfolio & Log

{selectedProduct.brand}

{selectedProduct.model}

{selectedProduct.size} SKU: {selectedProduct.sku}
{/* MANUAL ADJUSTER STOCK PANEL FOR AUTHORIZED STAFF */} {['owner', 'manager'].includes(currentStaff.role) ? (
Manual Stock Adjuster Node
setAdjustmentQty(Math.max(1, parseInt(e.target.value) || 0))} className="w-full text-xs font-mono border border-slate-200 bg-white p-2 rounded-xl outline-none focus:border-blue-500 shadow-inner" />
setAdjustmentReason(e.target.value)} className="w-full text-xs border border-slate-200 bg-white p-2 text-slate-700 outline-none focus:border-blue-500 rounded-xl" />
) : (
Manual adjustments restricted to Owner & Managers. Contact Zain Brother to restock.
)} {/* CHRONOLOGICAL HISTORICAL LEDGER FOR THE ACTIVE TIRE */}
Tire Action History {selectedProductHistory.length} ledger logs
{selectedProductHistory.length === 0 ? (
No matching transaction logs for this tire size yet.
) : ( selectedProductHistory.map((item) => { const isAddition = item.type === 'STOCK_IN'; const isReduction = item.type === 'STOCK_OUT'; return (
{new Date(item.dateTime).toLocaleString()}
{isAddition ? ( +{item.quantity} In ) : isReduction ? ( {item.quantity} Sold ) : ( Recount: {item.quantity > 0 ? `+${item.quantity}` : item.quantity} )}

{item.reason}

Adjusted by: {item.adjustedBy} Resulting Stock: {item.resultingStock}
); }) )}
)}
{/* CORE MODAL: NEW PRODUCT ADDITION FORM */} {showAddModal && (

Add Brand-New Tire to Database

Configure core sizing parameters, initial stock, and pricing thresholds

setNewSku(e.target.value)} className="w-full border border-slate-200 bg-white p-2 rounded-xl outline-none" />
setNewBrand(e.target.value)} className="w-full border border-slate-200 bg-white p-2 rounded-xl outline-none" />
setNewModel(e.target.value)} className="w-full border border-slate-200 bg-white p-2 rounded-xl outline-none" />
setNewSize(e.target.value)} className="w-full border border-slate-200 bg-white p-2 rounded-xl outline-none" />
setNewPurchasePrice(parseInt(e.target.value) || 0)} className="w-full font-mono border border-slate-200 bg-white p-2 rounded-xl outline-none" />
setNewPrice(parseInt(e.target.value) || 0)} className="w-full font-mono border border-slate-200 bg-white p-2 rounded-xl outline-none" />
setNewStock(parseInt(e.target.value) || 0)} className="w-full border border-slate-200 bg-white p-2 rounded-xl outline-none" />
setNewMinStock(parseInt(e.target.value) || 0)} className="w-full border border-slate-200 bg-white p-2 rounded-xl outline-none" />