import React, { useState, useMemo, useEffect } from 'react';
import { router } from '@inertiajs/react';
import {
    Search, X, Bike, Truck, DollarSign, Calendar, Plus,
    Layers, StickyNote, Tag, FileText, ShoppingCart,
    Trash2, Landmark, AlertTriangle, ArrowLeft, ClipboardList, Package, HelpCircle,
    RefreshCw, CheckCircle2, TrendingUp, Archive, AlertCircle
} from 'lucide-react';
import { IntegratedInput, IntegratedSelect, formatCurrency, getCurrentDate } from './CommonUI.tsx';

// --- Helper for Robust Data Extraction ---
const getPoItems = (po: any) => {
    if (!po) return [];
    let items = po.items || po.purchase_order_items || po.line_items || po.products;
    if (!items) return [];
    if (Array.isArray(items)) return items;
    if (typeof items === 'object') return Object.values(items);
    return [];
};

const getItemQty = (item: any) => {
    if (!item) return 0;
    const val = item.orderedQty ?? item.qty ?? item.quantity ?? item.ordered_qty ?? item.count ?? 0;
    return Number(val) || 0;
};

const getItemReceived = (item: any) => {
    if (!item) return 0;
    const val = item.receivedQty ?? item.received_qty ?? item.received ?? item.rec_qty ?? 0;
    return Number(val) || 0;
};

// Safe date formatter to prevent crashes
const safeDate = (dateStr: string) => {
    if (!dateStr) return 'N/A';
    const d = new Date(dateStr);
    return isNaN(d.getTime()) ? dateStr : d.toISOString().split('T')[0];
};

export function StockPage({ physicalStock = [], products = [], suppliers = [], purchaseOrders = [], accounts = [], notify }: any) {
    const [activeTab, setActiveTab] = useState<'stock' | 'po'>('stock');
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isPoModalOpen, setIsPoModalOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [isRefreshing, setIsRefreshing] = useState(false);

    // --- Manual Stock Entry State ---
    const [formData, setFormData] = useState({
        productId: '', engineNumber: '', chassisNumber: '', purchasePrice: '', paidAmount: '',
        supplierId: '', accountId: 'ACC-001', date: getCurrentDate(), notes: '',
        refNumber: '', condition: 'Brand New', stockType: 'Direct Purchase'
    });

    // --- Purchase Order Creation State ---
    const [poForm, setPoForm] = useState({
        supplierId: '', accountId: 'ACC-001', date: getCurrentDate(), expectedDate: '', refNumber: '', notes: '', paidAmount: ''
    });
    const [poItems, setPoItems] = useState<any[]>([]);
    const [currentItem, setCurrentItem] = useState({ productId: '', qty: '1', cost: '' });

    // --- Receive PO State ---
    const [isReceiveModalOpen, setIsReceiveModalOpen] = useState(false);
    const [receivingPo, setReceivingPo] = useState<any>(null);
    const [activeReceiveItem, setActiveReceiveItem] = useState<any>(null); // The specific item line being received
    const [receiveBatch, setReceiveBatch] = useState<any[]>([]); // Array of { engine, chassis }
    const [receivePayment, setReceivePayment] = useState(''); // Payment on receipt
    const [receiveAccount, setReceiveAccount] = useState(''); // Account to pay from
    const [receiveDate, setReceiveDate] = useState(getCurrentDate()); // Date of receipt
    const [receiveRef, setReceiveRef] = useState(''); // Reference / Challan Number for this batch

    // --- Data Helpers ---
    const safeProducts = useMemo(() => products || [], [products]);
    const safeSuppliers = useMemo(() => suppliers || [], [suppliers]);
    const safeAccounts = useMemo(() => accounts || [], [accounts]);

    const formattedProducts = useMemo(() => safeProducts.map((p: any) => ({
        id: p.id,
        label: `${p.make} ${p.model} (${p.color})`,
        cost: p.cost
    })), [safeProducts]);

    const calculatePoTotal = () => poItems.reduce((acc, item) => acc + (Number(item.qty) * Number(item.cost)), 0);

    const pendingPurchaseOrders = useMemo(() => {
        return (purchaseOrders || []).filter((po: any) => {
            const status = (po.status || 'Pending').toLowerCase();
            return status === 'pending' || status === 'partial';
        });
    }, [purchaseOrders]);

    // --- METRICS ---
    const stockStats = useMemo(() => {
        const count = physicalStock.length;
        const value = physicalStock.reduce((acc: number, s: any) => acc + (Number(s.purchasePrice) || 0), 0);
        return { count, value };
    }, [physicalStock]);

    const poStats = useMemo(() => {
        const pending = purchaseOrders.filter((po: any) => po.status !== 'Received');
        const count = pending.length;
        const committed = pending.reduce((acc: number, po: any) => acc + (Number(po.totalAmount) || 0), 0);
        let pendingUnits = 0;
        pending.forEach((po: any) => {
            const items = getPoItems(po);
            items.forEach((i: any) => {
                pendingUnits += (getItemQty(i) - getItemReceived(i));
            });
        });
        return { count, committed, pendingUnits };
    }, [purchaseOrders]);

    // --- Validation Logic ---
    const isDuplicateEngine = (engine: string) => {
        if (!engine) return false;
        const lowerEngine = engine.toLowerCase().trim();
        // Check current batch
        const inBatch = receiveBatch.filter(r => (r.engine || '').toLowerCase().trim() === lowerEngine).length > 1;
        // Check physical stock
        const inStock = physicalStock.some((s: any) => (s.engineNumber || '').toLowerCase() === lowerEngine);
        return inBatch || inStock;
    };

    const currentBatchValue = useMemo(() => {
        if (!activeReceiveItem || receiveBatch.length === 0) return 0;
        return receiveBatch.length * (activeReceiveItem.cost || 0);
    }, [receiveBatch, activeReceiveItem]);

    const canSubmitReceipt = useMemo(() => {
        if (!activeReceiveItem || receiveBatch.length === 0) return false;
        const allRowsValid = receiveBatch.every(r => r.engine && r.chassis && !isDuplicateEngine(r.engine));
        return allRowsValid;
    }, [activeReceiveItem, receiveBatch, physicalStock]);

    // --- Actions ---
    const handleRefresh = () => {
        setIsRefreshing(true);
        router.reload({
            only: ['physicalStock', 'purchaseOrders'],
            onFinish: () => {
                setIsRefreshing(false);
                if(notify) notify("Inventory Data Refreshed");
            }
        });
    };

    const handleSaveManualStock = () => {
        if(!formData.productId || !formData.engineNumber) return;
        router.post('/stock', formData, {
            onSuccess: () => {
                setIsModalOpen(false);
                setFormData({ productId: '', engineNumber: '', chassisNumber: '', purchasePrice: '', paidAmount: '', supplierId: '', accountId: 'ACC-001', date: getCurrentDate(), notes: '', refNumber: '', condition: 'Brand New', stockType: 'Direct Purchase' });
                if(notify) notify("Direct stock added successfully");
            }
        });
    };

    const handleAddPoItem = () => {
        if (!currentItem.productId || !currentItem.qty) return;
        const prod = safeProducts.find((p:any) => p.id == currentItem.productId);
        setPoItems([...poItems, {
            ...currentItem,
            uniqueId: Date.now(),
            productName: prod ? `${prod.make} ${prod.model}` : 'Unknown Product'
        }]);
        setCurrentItem({ productId: '', qty: '1', cost: '' });
    };

    const removePoItem = (id: number) => {
        setPoItems(poItems.filter(i => i.uniqueId !== id));
    };

    const handleSavePO = () => {
        if (!poForm.supplierId || poItems.length === 0) return;
        router.post('/purchase-orders', { ...poForm, items: poItems }, {
            onSuccess: () => {
                setIsPoModalOpen(false);
                setPoForm({ supplierId: '', accountId: 'ACC-001', date: getCurrentDate(), expectedDate: '', refNumber: '', notes: '', paidAmount: '' });
                setPoItems([]);
                if(notify) notify("Purchase Order Created");
            }
        });
    };

    // --- Receive Logic ---
    const startReceivingFlow = (po: any = null) => {
        const defaultAcc = po?.accountId || (safeAccounts.length > 0 ? safeAccounts[0]?.id : '');
        setReceivingPo(po);
        setActiveReceiveItem(null);
        setReceiveBatch([]);
        setReceivePayment('');
        setReceiveAccount(defaultAcc || '');
        setReceiveDate(getCurrentDate());
        setReceiveRef('');
        setIsReceiveModalOpen(true);
    };

    useEffect(() => {
        if (isReceiveModalOpen && receivingPo) {
            const items = getPoItems(receivingPo);
            const availableItems = items.filter((item: any) => {
                const ordered = getItemQty(item);
                const received = getItemReceived(item);
                return (ordered - received) > 0;
            });
            if (availableItems.length === 1 && !activeReceiveItem) {
                handleSelectReceiveItem(availableItems[0].id);
            }
        }
    }, [isReceiveModalOpen, receivingPo]);

    const handleSelectReceiveItem = (itemId: string) => {
        const items = getPoItems(receivingPo);
        const item = items.find((i:any) => i.id == itemId);
        if(item) {
            setActiveReceiveItem(item);
            setReceiveBatch([{ engine: '', chassis: '' }]);
        }
    };

    const updateReceiveRow = (index: number, field: string, value: string) => {
        const newBatch = [...receiveBatch];
        newBatch[index] = { ...newBatch[index], [field]: value };
        setReceiveBatch(newBatch);
    };

    const addReceiveRow = () => {
        const ordered = getItemQty(activeReceiveItem);
        const received = getItemReceived(activeReceiveItem);
        const remaining = ordered - received - receiveBatch.length;
        if(remaining > 0) {
            setReceiveBatch([...receiveBatch, { engine: '', chassis: '' }]);
        }
    };

    const removeReceiveRow = (index: number) => {
        setReceiveBatch(receiveBatch.filter((_, i) => i !== index));
    };

    const submitReceiveBatch = () => {
        if(!canSubmitReceipt) return;

        router.post(`/purchase-orders/${receivingPo.id}/receive`, {
            poId: receivingPo.id,
            paidAmount: receivePayment,
            accountId: receiveAccount,
            date: receiveDate,
            refNumber: receiveRef,
            items: receiveBatch.map(row => ({
                poItemId: activeReceiveItem.id,
                engine: row.engine,
                chassis: row.chassis
            }))
        }, {
            onSuccess: () => {
                setIsReceiveModalOpen(false);
                setReceivingPo(null);
                setReceiveBatch([]);
                if(notify) notify("Stock Units Received & Added to Inventory");
            }
        });
    };

    return (
        <div className="animate-fade-in space-y-6 leading-none">
            {/* Header / Stats Dashboard */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 px-4 lg:px-0">
                <div className="bg-slate-900 rounded-[2rem] p-6 text-white shadow-xl relative overflow-hidden flex flex-col justify-between group">
                    <div className="absolute right-0 top-0 p-4 opacity-10 group-hover:scale-110 transition-transform"><Layers size={80}/></div>
                    <div>
                        <p className="text-[10px] font-black text-cyan-400 uppercase tracking-widest mb-1">Total Asset Value</p>
                        <h3 className="text-2xl font-black font-mono tracking-tight">{formatCurrency(stockStats.value)}</h3>
                    </div>
                    <div className="flex items-center gap-2 mt-4 text-[9px] font-bold text-slate-400 uppercase">
                        <Package size={12}/> {stockStats.count} Physical Units Available
                    </div>
                </div>

                <div className="bg-white rounded-[2rem] p-6 border border-slate-200 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 bg-blue-50 text-blue-600 rounded-xl flex items-center justify-center shadow-inner"><ShoppingCart size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Committed Capital</p>
                        <p className="text-xl font-black text-slate-900 font-mono">{formatCurrency(poStats.committed)}</p>
                        <p className="text-[8px] font-bold text-blue-500 uppercase">In Pending Orders</p>
                    </div>
                </div>

                <div className="bg-white rounded-[2rem] p-6 border border-slate-200 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 bg-amber-50 text-amber-600 rounded-xl flex items-center justify-center shadow-inner"><Truck size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Incoming Stock</p>
                        <p className="text-xl font-black text-slate-900 font-mono">{poStats.pendingUnits}</p>
                        <p className="text-[8px] font-bold text-amber-500 uppercase">Units Awaiting Delivery</p>
                    </div>
                </div>

                <div className="bg-gradient-to-br from-emerald-500 to-emerald-600 rounded-[2rem] p-6 text-white shadow-lg flex flex-col justify-center items-center text-center cursor-pointer hover:shadow-emerald-500/30 transition-all" onClick={() => setIsModalOpen(true)}>
                    <div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center mb-2"><Plus size={20}/></div>
                    <p className="text-[10px] font-black uppercase tracking-widest">Quick Add Stock</p>
                </div>
            </div>

            {/* Navigation & Controls */}
            <div className="flex flex-col sm:flex-row justify-between items-center gap-4 px-4 lg:px-0 bg-white p-2 rounded-2xl border border-slate-100 shadow-sm">
                <div className="flex gap-2">
                    <button onClick={() => setActiveTab('stock')} className={`px-6 py-2.5 rounded-xl text-xs font-black uppercase tracking-widest transition-all flex items-center gap-2 ${activeTab === 'stock' ? 'bg-slate-900 text-white shadow-md' : 'text-slate-400 hover:bg-slate-50'}`}>
                        <Layers size={14} /> Physical Stock
                    </button>
                    <button onClick={() => setActiveTab('po')} className={`px-6 py-2.5 rounded-xl text-xs font-black uppercase tracking-widest transition-all flex items-center gap-2 ${activeTab === 'po' ? 'bg-slate-900 text-white shadow-md' : 'text-slate-400 hover:bg-slate-50'}`}>
                        <ShoppingCart size={14} /> Purchase Orders
                    </button>
                </div>

                <div className="flex gap-2 w-full sm:w-auto">
                    <div className="relative flex-1 sm:w-64">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={14} />
                        <input type="text" placeholder={activeTab === 'stock' ? "Search Engine/Chassis..." : "Search PO # or Supplier..."} className="w-full pl-9 pr-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs font-bold uppercase tracking-widest outline-none focus:bg-white focus:border-cyan-500 transition-all" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
                    </div>

                    <button onClick={handleRefresh} className={`px-3 py-2.5 bg-white border border-slate-200 text-slate-500 rounded-xl hover:bg-slate-50 transition-all ${isRefreshing ? 'animate-spin' : ''}`}>
                        <RefreshCw size={14} />
                    </button>

                    {activeTab === 'po' && (
                        <button onClick={() => setIsPoModalOpen(true)} className="px-6 py-2.5 bg-blue-600 text-white rounded-xl text-xs font-bold uppercase tracking-widest shadow-lg hover:bg-blue-700 transition-all flex items-center gap-2 whitespace-nowrap">
                            <Plus size={14} /> Create Order
                        </button>
                    )}
                </div>
            </div>

            {/* Main Content Tables */}
            {activeTab === 'stock' ? (
                <div className="bg-white rounded-[2.5rem] border border-slate-200 overflow-hidden shadow-sm mx-4 lg:mx-0">
                    <table className="w-full text-left">
                        <thead className="bg-slate-50 border-b border-slate-100 uppercase italic"><tr className="text-[10px] font-bold text-slate-500"><th className="px-8 py-5">Unit Details</th><th className="px-8 py-5">Identifiers</th><th className="px-8 py-5 text-right">Value</th><th className="px-8 py-5 text-center">Status</th></tr></thead>
                        <tbody className="divide-y divide-slate-100">
                        {physicalStock.filter((s: any) => {
                            const engine = (s.engineNumber || s.engine_number || '').toLowerCase();
                            const chassis = (s.chassisNumber || s.chassis_number || '').toLowerCase();
                            const term = searchTerm.toLowerCase();
                            return engine.includes(term) || chassis.includes(term);
                        }).map((s: any) => {
                            const prod = safeProducts.find((p: any) => p.id === (s.productId || s.product_id));
                            const engine = s.engineNumber || s.engine_number || '---';
                            const chassis = s.chassisNumber || s.chassis_number || '---';
                            const price = s.purchasePrice || s.purchase_price;
                            const date = safeDate(s.date || s.entry_date);

                            return (
                                <tr key={s.id} className="hover:bg-slate-50/50 transition-colors">
                                    <td className="px-8 py-5">
                                        <div className="flex items-center gap-3">
                                            <div className="w-10 h-10 rounded-xl bg-slate-100 flex items-center justify-center text-slate-400"><Bike size={18}/></div>
                                            <div>
                                                <p className="font-bold text-slate-900 text-sm uppercase">{prod ? `${prod.make} ${prod.model}` : 'Unknown'}</p>
                                                <p className="text-[10px] text-slate-500 font-bold uppercase tracking-widest mt-1">{prod?.color} • {date}</p>
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-8 py-5 text-xs font-mono"><div className="font-bold text-slate-700">ENG: {engine}</div><div className="text-slate-400 mt-0.5 font-medium uppercase">CHS: {chassis}</div></td>
                                    <td className="px-8 py-5 text-right font-black font-mono text-sm text-emerald-600">{formatCurrency(price)}</td>
                                    <td className="px-8 py-5 text-center">
                                        <span className="px-2 py-1 rounded text-[8px] font-black uppercase bg-emerald-50 text-emerald-600 border border-emerald-100 tracking-widest">Available</span>
                                    </td>
                                </tr>
                            )
                        })}
                        {physicalStock.length === 0 && <tr><td colSpan={4} className="p-12 text-center text-slate-400 text-xs font-bold uppercase italic">Inventory is empty</td></tr>}
                        </tbody>
                    </table>
                </div>
            ) : (
                <div className="bg-white rounded-[2.5rem] border border-slate-200 overflow-hidden shadow-sm mx-4 lg:mx-0">
                    <table className="w-full text-left">
                        <thead className="bg-slate-50 border-b border-slate-100 uppercase italic">
                        <tr className="text-[10px] font-bold text-slate-500">
                            <th className="px-8 py-5">Order Ref</th>
                            <th className="px-8 py-5">Supplier</th>
                            <th className="px-8 py-5">Fulfillment Progress</th>
                            <th className="px-8 py-5 text-right">Est. Value</th>
                            <th className="px-8 py-5 text-right">Actions</th>
                        </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                        {purchaseOrders.filter((po:any) => {
                            const ref = (po.refNumber || po.ref_number || '').toLowerCase();
                            const supName = (safeSuppliers.find((s:any)=>s.id=== (po.supplierId || po.supplier_id))?.name || '').toLowerCase();
                            const term = searchTerm.toLowerCase();
                            return ref.includes(term) || supName.includes(term);
                        }).map((po: any) => {
                            const items = getPoItems(po);
                            const totalOrdered = items.reduce((a:any, b:any) => a + getItemQty(b), 0);
                            const totalReceived = items.reduce((a:any, b:any) => a + getItemReceived(b), 0);
                            const percent = totalOrdered > 0 ? (totalReceived / totalOrdered) * 100 : 0;
                            const isPending = po.status !== 'Received';

                            return (
                                <tr key={po.id} className="hover:bg-slate-50/50 transition-colors group cursor-default">
                                    <td className="px-8 py-5">
                                        <div className="flex items-center gap-3">
                                            <div className="w-10 h-10 bg-blue-50 text-blue-600 rounded-xl flex items-center justify-center shrink-0"><FileText size={18}/></div>
                                            <div>
                                                <p className="text-xs font-black text-slate-900 uppercase tracking-widest font-mono">PO-{po.id.toString().substring(0,6)}</p>
                                                <p className="text-[10px] font-bold text-slate-400 uppercase mt-0.5">{safeDate(po.date)}</p>
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-8 py-5">
                                        <p className="font-bold text-slate-900 text-xs uppercase">{po.supplierName}</p>
                                        <p className="text-[10px] font-bold text-slate-400 uppercase mt-1 flex items-center gap-1"><Truck size={10} /> Vendor Record</p>
                                    </td>
                                    <td className="px-8 py-5">
                                        <div className="w-full max-w-xs">
                                            <div className="flex justify-between text-[9px] font-bold uppercase mb-1">
                                                <span className={isPending ? 'text-amber-600' : 'text-emerald-600'}>{isPending ? 'In Progress' : 'Completed'}</span>
                                                <span className="text-slate-400">{totalReceived}/{totalOrdered} Units</span>
                                            </div>
                                            <div className="w-full h-1.5 bg-slate-100 rounded-full overflow-hidden">
                                                <div className={`h-full transition-all duration-500 ${isPending ? 'bg-amber-500' : 'bg-emerald-500'}`} style={{width: `${percent}%`}}></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-8 py-5 text-right">
                                        <p className="font-black font-mono text-sm text-slate-900">{formatCurrency(po.totalAmount || 0)}</p>
                                    </td>
                                    <td className="px-8 py-5 text-right">
                                        {isPending ? (
                                            <button onClick={() => startReceivingFlow(po)} className="px-4 py-2 bg-slate-900 text-white rounded-xl text-[9px] font-black uppercase tracking-widest hover:bg-emerald-600 transition-all shadow-md inline-flex items-center gap-2">
                                                <ClipboardList size={12}/> Receive
                                            </button>
                                        ) : (
                                            <div className="inline-flex items-center gap-1 text-emerald-600 text-[10px] font-black uppercase tracking-widest bg-emerald-50 px-3 py-1 rounded-lg border border-emerald-100">
                                                <CheckCircle2 size={12}/> Closed
                                            </div>
                                        )}
                                    </td>
                                </tr>
                            );
                        })}
                        {purchaseOrders.length === 0 && (
                            <tr><td colSpan={5} className="p-12 text-center text-slate-400 text-xs font-bold uppercase italic">No active Purchase Orders found</td></tr>
                        )}
                        </tbody>
                    </table>
                </div>
            )}

            {/* Modal: Receive Stock (Multi-Step: Select PO -> Enter Items) */}
            {isReceiveModalOpen && (
                <div className="fixed inset-0 bg-slate-900/70 z-[110] flex items-center justify-center p-4 backdrop-blur-md overflow-y-auto leading-none">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-4xl shadow-2xl my-auto overflow-visible animate-fade-in relative flex flex-col max-h-[90vh]">
                        {/* HEADER */}
                        <div className="bg-emerald-600 p-8 flex justify-between items-center text-white shrink-0 rounded-t-[2.5rem]">
                            <div>
                                <h3 className="font-black uppercase text-sm tracking-widest italic font-heading">
                                    {receivingPo ? 'Receive Shipment Items' : 'Select Incoming Shipment'}
                                </h3>
                                <p className="text-[10px] font-bold opacity-80 uppercase tracking-widest mt-1">
                                    {receivingPo ? `PO-${receivingPo.id.toString().substring(0,8)} • ${receivingPo.supplierName}` : 'Choose a pending order to begin'}
                                </p>
                            </div>
                            <button onClick={() => setIsReceiveModalOpen(false)} className="hover:bg-white/20 p-2 rounded-full transition-colors"><X size={20} /></button>
                        </div>

                        {/* CONTENT */}
                        {!receivingPo ? (
                            // --- PHASE 1: SELECT PO ---
                            <div className="p-8 overflow-y-auto custom-scrollbar flex-1 min-h-[400px]">
                                {pendingPurchaseOrders.length === 0 ? (
                                    <div className="flex flex-col items-center justify-center h-full border-2 border-dashed border-slate-200 rounded-3xl p-10 text-center text-slate-400">
                                        <ClipboardList size={48} className="mb-4 text-slate-300"/>
                                        <p className="font-bold uppercase text-xs tracking-widest">No Pending Orders</p>
                                        <p className="text-[10px] opacity-70 mt-2 max-w-[200px]">All purchase orders have been received or none have been created yet.</p>
                                    </div>
                                ) : (
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        {pendingPurchaseOrders.map((po: any) => {
                                            const items = getPoItems(po);
                                            const totalOrdered = items.reduce((a:any, b:any) => a + getItemQty(b), 0);
                                            const totalReceived = items.reduce((a:any, b:any) => a + getItemReceived(b), 0);
                                            const percent = totalOrdered > 0 ? (totalReceived / totalOrdered) * 100 : 0;
                                            return (
                                                <div key={po.id} onClick={() => startReceivingFlow(po)} className="p-5 rounded-2xl border border-slate-200 hover:border-emerald-500 hover:shadow-lg hover:bg-emerald-50/10 cursor-pointer transition-all group bg-white">
                                                    <div className="flex justify-between items-center mb-3">
                                                        <span className="text-[10px] font-black bg-slate-100 text-slate-500 px-2 py-1 rounded border border-slate-200 uppercase tracking-widest">PO-{po.id.substring(0,6)}</span>
                                                        <span className="text-[10px] font-bold text-slate-400 uppercase">{safeDate(po.date)}</span>
                                                    </div>
                                                    <h4 className="font-black text-slate-900 text-sm uppercase truncate mb-1">{po.supplierName}</h4>
                                                    <p className="text-[10px] font-bold text-slate-400 uppercase">{totalOrdered} Units Ordered</p>
                                                    <div className="w-full h-1 bg-slate-100 rounded-full mt-3 overflow-hidden">
                                                        <div className="h-full bg-emerald-500 transition-all" style={{width: `${percent}%`}}></div>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                )}
                            </div>
                        ) : (
                            // --- PHASE 2: ENTER ITEMS ---
                            <>
                                <div className="p-8 overflow-y-auto custom-scrollbar flex-1 space-y-8">
                                    {/* Step 1: Select Item Line */}
                                    <div>
                                        <div className="flex justify-between items-end border-b border-slate-100 pb-2 mb-4">
                                            <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Ordered Items (Select One)</h4>
                                            <button onClick={() => setReceivingPo(null)} className="text-[10px] font-bold text-slate-400 hover:text-emerald-600 uppercase flex items-center gap-1 transition-colors"><ArrowLeft size={12} /> Change Order</button>
                                        </div>

                                        <div className="space-y-3">
                                            {getPoItems(receivingPo).map((item: any) => {
                                                const ordered = getItemQty(item);
                                                const received = getItemReceived(item);
                                                const remaining = ordered - received;
                                                const isActive = activeReceiveItem?.id === item.id;
                                                return (
                                                    <div
                                                        key={item.id}
                                                        onClick={() => remaining > 0 && handleSelectReceiveItem(item.id)}
                                                        className={`p-4 rounded-xl border flex justify-between items-center cursor-pointer transition-all ${
                                                            isActive ? 'bg-emerald-50 border-emerald-500 ring-1 ring-emerald-500' :
                                                                remaining <= 0 ? 'bg-slate-50 border-slate-100 opacity-60 cursor-not-allowed' : 'bg-white border-slate-200 hover:border-emerald-300'
                                                        }`}
                                                    >
                                                        <div>
                                                            <p className="text-xs font-black uppercase text-slate-900">{item.productName}</p>
                                                            <p className="text-[10px] text-slate-500 font-bold uppercase mt-0.5">{item.color}</p>
                                                        </div>
                                                        <div className="text-right">
                                                            <p className="text-[10px] font-bold text-slate-400 uppercase">Received / Ordered</p>
                                                            <p className="text-sm font-black font-mono">
                                                                <span className={remaining <= 0 ? 'text-emerald-600' : 'text-slate-900'}>{received}</span> / {ordered}
                                                            </p>
                                                        </div>
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    </div>

                                    {/* Step 2: Enter Details for Selected Item */}
                                    {activeReceiveItem ? (
                                        <div className="animate-fade-in">
                                            <div className="flex justify-between items-end border-b border-slate-100 pb-2 mb-4">
                                                <div className="flex items-center gap-4">
                                                    <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Enter Unit Details</h4>
                                                    <span className="px-2 py-1 bg-slate-100 rounded text-[8px] font-black uppercase text-slate-500 border border-slate-200">
                                                        Unit Cost: {formatCurrency(activeReceiveItem.cost)}
                                                    </span>
                                                </div>
                                                <button onClick={addReceiveRow} className="text-[10px] font-bold text-emerald-600 uppercase hover:underline flex items-center gap-1"><Plus size={12}/> Add Unit Line</button>
                                            </div>

                                            <div className="space-y-3">
                                                {receiveBatch.map((row, idx) => {
                                                    const duplicate = isDuplicateEngine(row.engine);
                                                    return (
                                                        <div key={idx} className="flex gap-3 items-center">
                                                            <div className="w-8 h-8 rounded-lg bg-slate-100 flex items-center justify-center text-[10px] font-black text-slate-500 shrink-0 border border-slate-200">{idx + 1}</div>
                                                            <div className="flex-1 relative">
                                                                <IntegratedInput
                                                                    placeholder="Engine Number"
                                                                    value={row.engine}
                                                                    onChange={(e: any) => updateReceiveRow(idx, 'engine', e.target.value)}
                                                                    icon={Bike}
                                                                />
                                                                {duplicate && (
                                                                    <div className="absolute right-2 top-1/2 -translate-y-1/2 text-rose-500 flex items-center gap-1 text-[9px] font-bold uppercase bg-white px-2 py-1 rounded shadow-sm border border-rose-100">
                                                                        <AlertCircle size={10}/> Duplicate
                                                                    </div>
                                                                )}
                                                            </div>
                                                            <div className="flex-1">
                                                                <IntegratedInput
                                                                    placeholder="Chassis Number"
                                                                    value={row.chassis}
                                                                    onChange={(e: any) => updateReceiveRow(idx, 'chassis', e.target.value)}
                                                                    icon={Layers}
                                                                />
                                                            </div>
                                                            <button onClick={() => removeReceiveRow(idx)} className="w-8 h-8 flex items-center justify-center text-rose-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition-colors"><Trash2 size={16}/></button>
                                                        </div>
                                                    );
                                                })}
                                                {receiveBatch.length === 0 && (
                                                    <div className="p-6 text-center text-slate-400 text-xs italic border-2 border-dashed border-slate-200 rounded-xl bg-slate-50/50">Click 'Add Unit Line' to input Engine/Chassis numbers</div>
                                                )}
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="p-8 text-center border-2 border-dashed border-slate-100 rounded-2xl bg-slate-50/30">
                                            <p className="text-xs font-bold text-slate-400 uppercase">Select an item above to begin receiving</p>
                                        </div>
                                    )}
                                </div>

                                <div className="p-6 bg-slate-50 border-t border-slate-200 shrink-0 rounded-b-[2.5rem]">
                                    {/* Batch Total Indicator */}
                                    {currentBatchValue > 0 && (
                                        <div className="flex justify-between items-center mb-4 px-1">
                                            <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Calculated Batch Value ({receiveBatch.length} Units)</span>
                                            <span className="text-sm font-black font-mono text-emerald-600">{formatCurrency(currentBatchValue)}</span>
                                        </div>
                                    )}

                                    <div className="flex justify-between items-end gap-4">
                                        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 flex-1">
                                            <IntegratedInput label="Receipt Date" type="date" value={receiveDate} onChange={(e:any) => setReceiveDate(e.target.value)} icon={Calendar} />
                                            <IntegratedInput label="Ref / Challan #" value={receiveRef} onChange={(e:any) => setReceiveRef(e.target.value)} icon={Tag} placeholder="Delivery Ref" />
                                            <IntegratedInput label="Amount Paid" value={receivePayment} onChange={(e:any) => setReceivePayment(e.target.value)} icon={DollarSign} placeholder="Partial / Full" />
                                            <IntegratedSelect label="Payment Source" value={receiveAccount} onChange={(e:any) => setReceiveAccount(e.target.value)} options={safeAccounts} displayKey="name" icon={Landmark} disabled={!receivePayment} />
                                        </div>
                                        <button
                                            onClick={submitReceiveBatch}
                                            disabled={!canSubmitReceipt}
                                            className="px-8 py-3 bg-emerald-600 text-white font-black uppercase text-xs tracking-widest rounded-xl hover:bg-emerald-700 transition-all shadow-lg disabled:opacity-50 disabled:grayscale mb-0.5 whitespace-nowrap"
                                        >
                                            Confirm Receipt
                                        </button>
                                    </div>
                                </div>
                            </>
                        )}
                    </div>
                </div>
            )}

            {/* Direct Stock Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 bg-slate-900/70 z-[110] flex items-center justify-center p-4 backdrop-blur-md overflow-y-auto leading-none">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-4xl shadow-2xl my-auto overflow-visible animate-fade-in relative">
                        <div className="bg-slate-950 p-8 flex justify-between items-center text-white rounded-t-[2.5rem]">
                            <h3 className="font-black uppercase text-sm tracking-widest italic font-heading">Direct Inventory Entry</h3>
                            <button onClick={() => setIsModalOpen(false)}><X size={20} /></button>
                        </div>
                        <div className="p-10 grid grid-cols-1 lg:grid-cols-12 gap-8">
                            <div className="lg:col-span-8 space-y-6">
                                <IntegratedSelect
                                    label="Model"
                                    value={formData.productId}
                                    onChange={(e: any) => {
                                        const p = safeProducts.find((prod: any) => prod.id == e.target.value);
                                        const cost = p ? p.cost.toString() : '';
                                        setFormData({...formData, productId: e.target.value, purchasePrice: cost, paidAmount: cost});
                                    }}
                                    options={formattedProducts}
                                    displayKey="label"
                                    icon={Layers}
                                />
                                <div className="grid grid-cols-2 gap-4">
                                    <IntegratedInput label="Engine #" value={formData.engineNumber} onChange={(e: any) => setFormData({...formData, engineNumber: e.target.value})} icon={Bike} />
                                    <IntegratedInput label="Chassis #" value={formData.chassisNumber} onChange={(e: any) => setFormData({...formData, chassisNumber: e.target.value})} icon={Bike} />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <IntegratedInput label="Unit Cost" value={formData.purchasePrice} onChange={(e: any) => setFormData({...formData, purchasePrice: e.target.value})} icon={DollarSign} />
                                    <IntegratedInput label="Amount Paid" value={formData.paidAmount} onChange={(e: any) => setFormData({...formData, paidAmount: e.target.value})} icon={DollarSign} placeholder="Partial or 0 for credit" />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <IntegratedInput label="Date" type="date" value={formData.date} onChange={(e: any) => setFormData({...formData, date: e.target.value})} icon={Calendar} />
                                    <IntegratedSelect label="Supplier" value={formData.supplierId} onChange={(e: any) => setFormData({...formData, supplierId: e.target.value})} options={safeSuppliers} displayKey="name" icon={Truck} />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <IntegratedSelect label="Debit Account" value={formData.accountId} onChange={(e: any) => setFormData({...formData, accountId: e.target.value})} options={safeAccounts} displayKey="name" icon={Landmark} />
                                    <IntegratedInput label="Reference #" value={formData.refNumber} onChange={(e: any) => setFormData({...formData, refNumber: e.target.value})} icon={Tag} placeholder="Invoice Ref" />
                                </div>
                            </div>
                            <div className="lg:col-span-4 flex items-end">
                                <button onClick={handleSaveManualStock} className="w-full bg-slate-900 text-white py-6 rounded-3xl font-black uppercase text-xs tracking-widest hover:bg-black transition-all shadow-xl">Authorize Entry</button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* PO Creation Modal */}
            {isPoModalOpen && (
                <div className="fixed inset-0 bg-slate-900/70 z-[110] flex items-center justify-center p-4 backdrop-blur-md overflow-y-auto leading-none">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-5xl shadow-2xl my-auto overflow-visible animate-fade-in relative flex flex-col max-h-[90vh]">
                        <div className="bg-blue-600 p-8 flex justify-between items-center text-white shrink-0 rounded-t-[2.5rem]">
                            <h3 className="font-black uppercase text-sm tracking-widest italic font-heading">New Purchase Order</h3>
                            <button onClick={() => setIsPoModalOpen(false)} className="hover:bg-white/20 p-2 rounded-full transition-colors"><X size={20} /></button>
                        </div>

                        <div className="p-8 overflow-y-auto custom-scrollbar flex-1">
                            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                                {/* Left: PO Details */}
                                <div className="lg:col-span-1 space-y-6">
                                    <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100 pb-2">Order Details</h4>
                                    <IntegratedSelect label="Supplier" value={poForm.supplierId} onChange={(e:any) => setPoForm({...poForm, supplierId: e.target.value})} options={safeSuppliers} displayKey="name" icon={Truck} />
                                    <IntegratedInput label="Order Date" type="date" value={poForm.date} onChange={(e:any) => setPoForm({...poForm, date: e.target.value})} icon={Calendar} />
                                    <IntegratedInput label="Expected Delivery" type="date" value={poForm.expectedDate} onChange={(e:any) => setPoForm({...poForm, expectedDate: e.target.value})} icon={Calendar} />

                                    <div className="space-y-4 pt-4 border-t border-slate-100">
                                        <IntegratedInput label="Advance Payment" value={poForm.paidAmount} onChange={(e:any) => setPoForm({...poForm, paidAmount: e.target.value})} icon={DollarSign} placeholder="0 if none" />
                                        <IntegratedSelect label="Payment Account" value={poForm.accountId} onChange={(e:any) => setPoForm({...poForm, accountId: e.target.value})} options={safeAccounts} displayKey="name" icon={Landmark} />
                                    </div>

                                    <IntegratedInput label="Ref Number" value={poForm.refNumber} onChange={(e:any) => setPoForm({...poForm, refNumber: e.target.value})} icon={Tag} />
                                    <IntegratedInput label="Notes" value={poForm.notes} onChange={(e:any) => setPoForm({...poForm, notes: e.target.value})} icon={StickyNote} />
                                </div>

                                {/* Right: Items Builder */}
                                <div className="lg:col-span-2 space-y-6 flex flex-col">
                                    <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100 pb-2">Line Items</h4>

                                    {/* Add Item Row */}
                                    <div className="flex gap-2 items-end bg-slate-50 p-4 rounded-2xl border border-slate-100">
                                        <div className="flex-1"><IntegratedSelect label="Product" value={currentItem.productId} onChange={(e:any) => { const p = safeProducts.find((pr:any)=>pr.id == e.target.value); setCurrentItem({...currentItem, productId: e.target.value, cost: p?.cost?.toString() || ''}); }} options={formattedProducts} displayKey="label" placeholder="Select Model" /></div>
                                        <div className="w-20"><IntegratedInput label="Qty" type="number" value={currentItem.qty} onChange={(e:any) => setCurrentItem({...currentItem, qty: e.target.value})} /></div>
                                        <div className="w-32"><IntegratedInput label="Unit Cost" value={currentItem.cost} onChange={(e:any) => setCurrentItem({...currentItem, cost: e.target.value})} /></div>
                                        <button onClick={handleAddPoItem} className="h-10 w-10 bg-slate-900 text-white rounded-xl flex items-center justify-center hover:bg-black transition-colors shrink-0 mb-0.5"><Plus size={18}/></button>
                                    </div>

                                    {/* Items List */}
                                    <div className="flex-1 bg-white border border-slate-200 rounded-2xl overflow-hidden min-h-[200px]">
                                        <table className="w-full text-left">
                                            <thead className="bg-slate-50 text-[9px] font-black uppercase text-slate-500">
                                            <tr><th className="px-4 py-3">Item</th><th className="px-4 py-3 text-center">Qty</th><th className="px-4 py-3 text-right">Cost</th><th className="px-4 py-3 text-right">Total</th><th className="px-4 py-3"></th></tr>
                                            </thead>
                                            <tbody className="divide-y divide-slate-100">
                                            {poItems.map((item, idx) => (
                                                <tr key={item.uniqueId}>
                                                    <td className="px-4 py-3 text-xs font-bold text-slate-700">{item.productName}</td>
                                                    <td className="px-4 py-3 text-center text-xs font-bold">{item.qty}</td>
                                                    <td className="px-4 py-3 text-right text-xs font-mono">{formatCurrency(item.cost)}</td>
                                                    <td className="px-4 py-3 text-right text-xs font-mono font-black">{formatCurrency(item.qty * item.cost)}</td>
                                                    <td className="px-4 py-3 text-right"><button onClick={() => removePoItem(item.uniqueId)} className="text-rose-500 hover:text-rose-700"><Trash2 size={14}/></button></td>
                                                </tr>
                                            ))}
                                            {poItems.length === 0 && <tr><td colSpan={5} className="p-8 text-center text-slate-400 text-xs font-bold uppercase italic">No items added yet</td></tr>}
                                            </tbody>
                                        </table>
                                    </div>

                                    <div className="flex justify-between items-center bg-slate-900 text-white p-6 rounded-2xl shadow-xl">
                                        <div className="text-xs font-bold uppercase tracking-widest opacity-70">Grand Total Estimate</div>
                                        <div className="text-2xl font-black font-mono">{formatCurrency(calculatePoTotal())}</div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="p-6 bg-slate-50 border-t border-slate-200 flex justify-end gap-4 shrink-0 rounded-b-[2.5rem]">
                            <button onClick={() => setIsPoModalOpen(false)} className="px-6 py-3 text-slate-500 font-bold uppercase text-xs tracking-widest hover:bg-slate-100 rounded-xl transition-all">Cancel</button>
                            <button onClick={handleSavePO} disabled={poItems.length === 0} className="px-8 py-3 bg-blue-600 text-white font-black uppercase text-xs tracking-widest rounded-xl hover:bg-blue-700 transition-all shadow-lg disabled:opacity-50 disabled:grayscale">Finalize Order</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
