
import React, { useState, useMemo, useEffect } from 'react';
import {
    DollarSign, HandCoins, ShoppingBag, Search, X,
    CalendarDays, User, Bike, Hash, Binary, Printer, Pencil, PackageCheck,
    Activity, Landmark, BadgeCheck, TrendingUp, Layers, CheckCircle2,
    Clock, Banknote, History, Info, Loader2, Eye, Receipt,
    ArrowUpRight, ChevronRight, FileText, Smartphone, MapPin, Plus
} from 'lucide-react';
import { router } from '@inertiajs/react';
import { IntegratedInput, IntegratedSelect, formatCurrency, getCurrentDate } from './CommonUI.tsx';

export function TerminalPage({ products, customers, accounts, salesHistory, physicalStock, notify, errors }: any) {
    // --- UI States ---
    const [isSaleModalOpen, setIsSaleModalOpen] = useState(false);
    const [viewingSale, setViewingSale] = useState<any>(null);
    const [isProcessing, setIsProcessing] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');

    // --- Form States ---
    const [saleFormData, setSaleFormData] = useState({
        date: getCurrentDate(),
        customerId: '',
        productId: '',
        engineNumber: '',
        chassisNumber: '',
        totalPrice: '',
        downPayment: '',
        installmentsCount: '0',
        monthlyAmount: '',
        notes: '',
        paymentType: 'Full Payment',
        accountId: 'ACC-001',
        refNumber: ''
    });

    // Auto-calculate logic: Mode Switching Defaults
    useEffect(() => {
        if (saleFormData.paymentType === 'Full Payment') {
            // For Full Payment, Down Payment matches Total Price automatically
            setSaleFormData(prev => ({
                ...prev,
                downPayment: prev.totalPrice,
                installmentsCount: '0',
                monthlyAmount: '0'
            }));
        } else {
            // For Installments, default count if 0
            setSaleFormData(prev => {
                // Fix: Clear down payment if it matches total price (leftover from Full Payment mode)
                // so the user can enter the actual down payment/advance.
                const isAutoFull = prev.downPayment === prev.totalPrice && prev.totalPrice !== '';

                return {
                    ...prev,
                    downPayment: isAutoFull ? '' : prev.downPayment,
                    installmentsCount: prev.installmentsCount === '0' ? '12' : prev.installmentsCount
                };
            });
        }
    }, [saleFormData.totalPrice, saleFormData.paymentType]);

    // Auto-calculate logic: Math for Monthly Installments
    useEffect(() => {
        if (saleFormData.paymentType === 'Lease/Installments') {
            const total = parseFloat(saleFormData.totalPrice) || 0;
            const down = parseFloat(saleFormData.downPayment) || 0;
            const months = parseFloat(saleFormData.installmentsCount) || 0;

            // Calculate Balance
            const balance = Math.max(0, total - down);

            // Calculate Monthly
            let monthly = 0;
            if (months > 0 && balance > 0) {
                monthly = Math.round(balance / months);
            }

            setSaleFormData(prev => {
                // Only update if changed to avoid unnecessary renders
                if (prev.monthlyAmount !== monthly.toString()) {
                    return { ...prev, monthlyAmount: monthly.toString() };
                }
                return prev;
            });
        }
    }, [saleFormData.totalPrice, saleFormData.downPayment, saleFormData.installmentsCount, saleFormData.paymentType]);

    // --- Data Normalization ---
    // Fixes "PKR 0" issue by handling both 'total' (frontend mock) and 'total_amount' (backend eloquent)
    const normalizedSales = useMemo(() => {
        return (salesHistory || []).map((s: any) => {
            const total = Number(s.total ?? s.total_amount ?? 0) || 0;
            const paid = (s.payments || []).reduce((acc: number, p: any) => acc + (Number(p.amount) || 0), 0);
            return {
                ...s,
                total,
                paidAmount: paid,
                balance: total - paid,
                isCleared: (total - paid) <= 0
            };
        });
    }, [salesHistory]);

    // --- Memos & Statistics ---
    const salesStats = useMemo(() => {
        const today = getCurrentDate();
        const todaySales = normalizedSales.filter((s:any) => s.date === today);
        const revenue = todaySales.reduce((acc:number, s:any) => acc + s.total, 0);
        const leaseOut = normalizedSales.filter((s:any) => s.paymentType !== 'Full Payment');
        const outstanding = leaseOut.reduce((acc:number, s:any) => acc + s.balance, 0);

        return { revenue, count: todaySales.length, outstanding, totalCount: normalizedSales.length };
    }, [normalizedSales]);

    const formattedProducts = useMemo(() => (products || []).map((p: any) => ({
        id: p.id,
        label: `${p.make} ${p.model} (${p.color})`,
        price: p.price,
        availCount: (physicalStock || []).filter((u: any) => u.productId === p.id).length
    })), [products, physicalStock]);

    const availableUnits = useMemo(() =>
            (physicalStock || []).filter((unit: any) => unit.productId === saleFormData.productId),
        [physicalStock, saleFormData.productId]
    );

    const availableUnitOptions = useMemo(() =>
            availableUnits.map((u: any) => ({ ...u, id: u.engineNumber, originalId: u.id })),
        [availableUnits]
    );

    const filteredSales = useMemo(() => {
        if (!searchTerm) return normalizedSales;
        const lower = searchTerm.toLowerCase();
        return normalizedSales.filter((s: any) => {
            // FIX: Handle both string and object for customer
            const custName = typeof s.customer === 'object' ? s.customer.name : s.customer;
            const engine = typeof s.engine === 'object' ? s.engine.engine_number : s.engine;

            return (
                String(custName || '').toLowerCase().includes(lower) ||
                String(s.id).toLowerCase().includes(lower) ||
                String(engine || '').toLowerCase().includes(lower)
            );
        });
    }, [normalizedSales, searchTerm]);

    // --- Handlers ---
    const handleSaleSubmit = () => {
        if (!Number(saleFormData.totalPrice)) return; // Prevent 0 value sales

        setIsProcessing(true);
        router.post('/sales/store', saleFormData, {
            onSuccess: () => {
                setIsSaleModalOpen(false);
                notify('Sale Invoiced Successfully');
                setIsProcessing(false);
                resetForm();
            },
            onError: () => setIsProcessing(false),
            onFinish: () => setIsProcessing(false)
        });
    };

    const resetForm = () => {
        setSaleFormData({
            date: getCurrentDate(), customerId: '', productId: '', engineNumber: '',
            chassisNumber: '', totalPrice: '', downPayment: '', installmentsCount: '0',
            monthlyAmount: '', notes: '', paymentType: 'Full Payment',
            accountId: 'ACC-001', refNumber: ''
        });
    };

    return (
        <div className="animate-fade-in space-y-8 pb-20">
            {/* KPI Sales Dashboard */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg: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 group">
                    <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:scale-110 transition-transform"><TrendingUp size={80}/></div>
                    <p className="text-[10px] font-black text-cyan-400 uppercase tracking-widest mb-1.5">Today's Revenue</p>
                    <h3 className="text-2xl font-black font-mono leading-none">{formatCurrency(salesStats.revenue)}</h3>
                    <div className="mt-4 flex items-center gap-2">
                        <span className="text-[10px] font-bold text-slate-400 uppercase tracking-tight">{salesStats.count} Units Checkout</span>
                    </div>
                </div>
                <div className="bg-white rounded-[2rem] p-6 border border-slate-200 shadow-sm flex items-center gap-4">
                    <div className="w-14 h-14 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0 shadow-inner"><HandCoins size={28} /></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Portfolio Recovery</p>
                        <p className="text-xl font-black text-slate-900 font-mono leading-none">{formatCurrency(salesStats.outstanding)}</p>
                        <p className="text-[9px] font-bold text-rose-500 uppercase mt-2">Active Lease Balances</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-14 h-14 rounded-2xl bg-cyan-50 text-cyan-600 flex items-center justify-center shrink-0 shadow-inner"><ShoppingBag size={28} /></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Database Volume</p>
                        <p className="text-xl font-black text-slate-900 font-mono leading-none">{salesStats.totalCount} Total Invoices</p>
                        <p className="text-[9px] font-bold text-slate-400 uppercase mt-2">System Wide Archival</p>
                    </div>
                </div>
                <div className="bg-white rounded-[2rem] p-6 border-2 border-dashed border-slate-200 flex flex-col items-center justify-center group cursor-pointer hover:border-cyan-500 hover:bg-cyan-50/30 transition-all" onClick={() => setIsSaleModalOpen(true)}>
                    <div className="w-10 h-10 rounded-full bg-slate-100 group-hover:bg-cyan-500 group-hover:text-white flex items-center justify-center text-slate-400 transition-colors mb-2"><Plus size={20}/></div>
                    <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 group-hover:text-cyan-600">New Checkout</p>
                </div>
            </div>

            {/* Control Bar */}
            <div className="flex flex-col sm:flex-row justify-between items-center gap-4 px-4 lg:px-0">
                <div className="relative w-full sm:w-96">
                    <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
                    <input
                        type="text"
                        placeholder="Search by Client, Engine or Invoice..."
                        className="w-full pl-11 pr-4 py-4 bg-white border border-slate-200 rounded-2xl text-[11px] font-black uppercase tracking-[0.1em] outline-none focus:border-cyan-500 shadow-sm transition-all placeholder:text-slate-300"
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                    />
                </div>
                <div className="flex gap-3 w-full sm:w-auto">
                    <button className="flex-1 sm:flex-none px-6 py-4 bg-white border border-slate-200 text-slate-600 rounded-2xl text-[10px] font-black uppercase tracking-widest shadow-sm hover:bg-slate-50 transition-all flex items-center justify-center gap-2">
                        <Printer size={14}/> Batch Print
                    </button>
                    <button onClick={() => setIsSaleModalOpen(true)} className="flex-1 sm:flex-none px-8 py-4 bg-slate-950 text-white rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] shadow-xl hover:shadow-cyan-500/10 transition-all flex items-center justify-center gap-2">
                        <PackageCheck size={16} /> Terminal Checkout
                    </button>
                </div>
            </div>

            {/* Sales Ledger Table */}
            <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-6">Transaction Entity</th>
                        <th className="px-8 py-6 text-center">Payment Lifecycle</th>
                        <th className="px-8 py-6">Vehicle Unit Identity</th>
                        <th className="px-8 py-6 text-right">Settlement Volume</th>
                        <th className="px-8 py-6 text-right">Workflow</th>
                    </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                    {filteredSales.map((s: any) => {
                        // Use pre-calculated normalized values
                        const customerName = typeof s.customer === 'object' ? s.customer.name : s.customer;

                        return (
                            <tr key={s.id} className="hover:bg-slate-50/50 transition-colors group">
                                <td className="px-8 py-6">
                                    <div className="flex items-center gap-4">
                                        <div className="w-10 h-10 rounded-full bg-slate-100 flex items-center justify-center text-slate-400 group-hover:bg-cyan-50 group-hover:text-cyan-600 transition-colors"><User size={18}/></div>
                                        <div>
                                            <p className="font-black text-slate-900 text-sm uppercase tracking-tight">{customerName}</p>
                                            <p className="text-[10px] text-cyan-600 font-black uppercase font-mono mt-1">ID: {s.id} • {s.date}</p>
                                        </div>
                                    </div>
                                </td>
                                <td className="px-8 py-6 text-center">
                                    <div className="flex flex-col items-center gap-2">
                                <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[8px] font-black uppercase border tracking-widest ${
                                    s.isCleared ? 'bg-emerald-50 text-emerald-600 border-emerald-100' : 'bg-amber-50 text-amber-600 border-amber-100'
                                }`}>
                                    {s.isCleared ? <CheckCircle2 size={10}/> : <History size={10}/>}
                                    {s.isCleared ? 'Fully Settled' : 'Active Recovery'}
                                </span>
                                        {s.paymentType !== 'Full Payment' && !s.isCleared && (
                                            <div className="w-24 h-1 bg-slate-100 rounded-full overflow-hidden">
                                                <div className="h-full bg-indigo-500" style={{width: `${(s.paidAmount/s.total)*100}%`}}></div>
                                            </div>
                                        )}
                                    </div>
                                </td>
                                <td className="px-8 py-6">
                                    <div className="flex items-center gap-3">
                                        <Bike size={14} className="text-slate-300"/>
                                        <div>
                                            <p className="text-xs font-black text-slate-700 uppercase tracking-tight">{s.bike}</p>
                                            <p className="text-[9px] font-mono text-slate-400 uppercase font-bold mt-0.5">ENG: {s.engine}</p>
                                        </div>
                                    </div>
                                </td>
                                <td className="px-8 py-6 text-right font-black font-mono text-sm text-slate-900">
                                    {formatCurrency(s.total)}
                                    {s.balance > 0 && <p className="text-[8px] text-rose-500 font-bold uppercase mt-1">Bal: {formatCurrency(s.balance)}</p>}
                                </td>
                                <td className="px-8 py-6 text-right">
                                    <div className="flex justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                        <button onClick={() => setViewingSale(s)} className="p-2.5 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-xl transition-all"><Eye size={16}/></button>
                                        <button className="p-2.5 text-slate-400 hover:text-emerald-600 hover:bg-emerald-50 rounded-xl transition-all"><Printer size={16}/></button>
                                    </div>
                                </td>
                            </tr>
                        );
                    })}
                    {filteredSales.length === 0 && (
                        <tr><td colSpan={5} className="p-24 text-center text-slate-300 uppercase italic font-black text-[10px] tracking-[0.3em]">Operational Terminal Active • No Sales Logged</td></tr>
                    )}
                    </tbody>
                </table>
            </div>

            {/* MODAL: CHECKOUT TERMINAL */}
            {isSaleModalOpen && (
                <div className="fixed inset-0 bg-slate-950/80 z-[100] flex items-center justify-center p-4 backdrop-blur-xl overflow-y-auto leading-none">
                    <div className="bg-white rounded-[3rem] w-full max-w-5xl shadow-2xl border border-white/10 my-auto animate-fade-in relative overflow-visible">
                        {/* Modal Header */}
                        <div className="bg-slate-900 p-8 flex justify-between items-center text-white border-b border-white/5 rounded-t-[3rem]">
                            <div className="flex items-center gap-5">
                                <div className="w-14 h-14 bg-cyan-500 rounded-2xl flex items-center justify-center text-slate-900 shadow-lg shadow-cyan-500/20"><ShoppingBag size={28} /></div>
                                <div className="leading-none">
                                    <h3 className="font-black uppercase italic text-lg tracking-widest leading-none">Terminal Checkout</h3>
                                    <p className="text-[10px] font-bold text-cyan-400 uppercase tracking-[0.3em] mt-2 leading-none">Authorized Transaction Protocol</p>
                                </div>
                            </div>
                            <button onClick={() => setIsSaleModalOpen(false)} className="p-3 bg-white/5 hover:bg-rose-500/20 rounded-full transition-all leading-none text-white"><X size={24} /></button>
                        </div>

                        <div className="p-10 grid grid-cols-1 lg:grid-cols-12 gap-10">
                            {/* Left: Input Sections */}
                            <div className="lg:col-span-8 space-y-10">
                                {/* Section 1: Identity */}
                                <div className="space-y-5">
                                    <div className="flex items-center gap-3 border-b border-slate-100 pb-3">
                                        <div className="w-6 h-6 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center font-black text-[10px]">01</div>
                                        <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Customer Entity & Timeline</h4>
                                    </div>
                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
                                        <div className="md:col-span-2">
                                            <IntegratedSelect label="Registered Client Name" value={saleFormData.customerId} onChange={(e: any) => setSaleFormData({...saleFormData, customerId: e.target.value})} options={customers} displayKey="name" icon={User} />
                                            {errors.customerId && <p className="text-[9px] font-black text-rose-500 uppercase mt-2 ml-1">{errors.customerId}</p>}
                                        </div>
                                        <IntegratedInput label="Sale Timestamp" type="date" value={saleFormData.date} onChange={(e: any) => setSaleFormData({...saleFormData, date: e.target.value})} icon={CalendarDays} />
                                    </div>
                                </div>

                                {/* Section 2: Product Allocation */}
                                <div className="space-y-5">
                                    <div className="flex items-center gap-3 border-b border-slate-100 pb-3">
                                        <div className="w-6 h-6 rounded-lg bg-cyan-50 text-cyan-600 flex items-center justify-center font-black text-[10px]">02</div>
                                        <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Vehicle Selection & Physical Audit</h4>
                                    </div>
                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
                                        <div className="md:col-span-2">
                                            <IntegratedSelect
                                                label="Vehicle Model Variant"
                                                value={saleFormData.productId}
                                                onChange={(e: any) => {
                                                    const p = products.find((prod: any) => prod.id === e.target.value);
                                                    setSaleFormData({...saleFormData, productId: e.target.value, totalPrice: p ? p.price.toString() : '', engineNumber: '', chassisNumber: ''});
                                                }}
                                                options={formattedProducts}
                                                displayKey="label"
                                                icon={Bike}
                                            />
                                        </div>
                                        <IntegratedInput label="Sale Order ID" value={saleFormData.refNumber} onChange={(e: any) => setSaleFormData({...saleFormData, refNumber: e.target.value})} icon={Hash} placeholder="e.g. SO-992" />

                                        <div className="md:col-span-3 p-6 bg-slate-50 rounded-3xl border border-slate-100 space-y-5 shadow-inner">
                                            <div className="flex items-center justify-between">
                                                <p className="text-[9px] font-black text-slate-500 uppercase tracking-widest flex items-center gap-2"><PackageCheck size={14} className="text-cyan-500" /> Unit Serialization Verification</p>
                                                {saleFormData.productId && (
                                                    <span className={`px-2 py-0.5 rounded text-[8px] font-black uppercase ${availableUnits.length > 0 ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'}`}>
                                            {availableUnits.length} Units Available in stock
                                        </span>
                                                )}
                                            </div>
                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                                                <div className="md:col-span-2">
                                                    <IntegratedSelect
                                                        label="Assign Unit by Engine Serial"
                                                        value={saleFormData.engineNumber}
                                                        onChange={(e: any) => {
                                                            const unit = availableUnits.find((u: any) => u.engineNumber === e.target.value);
                                                            setSaleFormData({...saleFormData, engineNumber: e.target.value, chassisNumber: unit?.chassisNumber || ''});
                                                        }}
                                                        options={availableUnitOptions}
                                                        displayKey="engineNumber"
                                                        placeholder={availableUnits.length > 0 ? "Select Engine Number..." : "Verify stock availability"}
                                                        icon={Layers}
                                                    />
                                                </div>
                                                <IntegratedInput label="Chassis ID (Verified)" value={saleFormData.chassisNumber} disabled icon={Binary} />
                                                <div className="flex items-center gap-3 px-4 py-2 bg-white rounded-xl border border-slate-200">
                                                    <Info size={14} className="text-amber-500 shrink-0" />
                                                    <p className="text-[8px] font-bold text-slate-400 uppercase leading-tight">Proceeding locks this serial into the sale. Serial cannot be reused.</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                {/* Section 3: Financials */}
                                <div className="space-y-5">
                                    <div className="flex items-center gap-3 border-b border-slate-100 pb-3">
                                        <div className="w-6 h-6 rounded-lg bg-emerald-50 text-emerald-600 flex items-center justify-center font-black text-[10px]">03</div>
                                        <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Financial Settlement Details</h4>
                                    </div>
                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
                                        <IntegratedInput label="Negotiated Sale Price (PKR)" value={saleFormData.totalPrice} onChange={(e: any) => setSaleFormData({...saleFormData, totalPrice: e.target.value})} icon={DollarSign} />
                                        <IntegratedSelect label="Payment Structure" value={saleFormData.paymentType} onChange={(e: any) => setSaleFormData({...saleFormData, paymentType: e.target.value})} options={['Full Payment', 'Lease/Installments']} icon={Activity} />
                                        <IntegratedSelect label="Target Receipt Account" value={saleFormData.accountId} onChange={(e: any) => setSaleFormData({...saleFormData, accountId: e.target.value})} options={accounts} displayKey="name" icon={Landmark} />
                                    </div>

                                    <div className={`p-6 rounded-3xl border-2 transition-all duration-300 ${saleFormData.paymentType === 'Full Payment' ? 'bg-emerald-50/50 border-emerald-100' : 'bg-indigo-50/50 border-indigo-100'}`}>
                                        {saleFormData.paymentType === 'Full Payment' ? (
                                            <div className="grid grid-cols-1">
                                                <IntegratedInput
                                                    label="Amount Received Now (PKR)"
                                                    value={saleFormData.downPayment}
                                                    onChange={(e:any) => setSaleFormData({...saleFormData, downPayment: e.target.value})}
                                                    icon={DollarSign}
                                                    placeholder="Verify full amount received"
                                                />
                                                <p className="text-[9px] font-bold text-slate-400 mt-2 flex items-center gap-1">
                                                    <Info size={12} /> Auto-filled to match Sale Price. Adjust if providing discount or partial cash.
                                                </p>
                                            </div>
                                        ) : (
                                            <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
                                                <IntegratedInput label="Down Payment / Advance" value={saleFormData.downPayment} onChange={(e:any) => setSaleFormData({...saleFormData, downPayment: e.target.value})} icon={DollarSign} />
                                                <IntegratedInput label="Total Installments" value={saleFormData.installmentsCount} onChange={(e:any) => setSaleFormData({...saleFormData, installmentsCount: e.target.value})} icon={Clock} />
                                                <IntegratedInput label="Monthly Installment" value={saleFormData.monthlyAmount} onChange={(e:any) => setSaleFormData({...saleFormData, monthlyAmount: e.target.value})} icon={Banknote} />
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Right: Summary Sidebar */}
                            <div className="lg:col-span-4 space-y-6">
                                <div className="bg-slate-50 p-8 rounded-[2.5rem] border border-slate-100 space-y-6 h-full flex flex-col">
                                    <h4 className="text-[10px] font-black text-slate-900 uppercase tracking-widest border-b border-slate-200 pb-3 italic">Transaction Summary</h4>

                                    <div className="space-y-6 flex-1">
                                        <div className="space-y-1.5">
                                            <p className="text-[8px] font-black text-slate-400 uppercase leading-none">Invoicing To</p>
                                            <p className="text-sm font-black text-slate-900 uppercase truncate">
                                                {customers.find((c:any) => c.id === saleFormData.customerId)?.name || 'Unidentified Client'}
                                            </p>
                                        </div>

                                        <div className="space-y-1.5">
                                            <p className="text-[8px] font-black text-slate-400 uppercase leading-none">Vehicle Specs</p>
                                            <p className="text-sm font-black text-slate-900 uppercase">
                                                {products.find((p:any) => p.id === saleFormData.productId)?.model || 'No Model Selected'}
                                            </p>
                                            <p className="text-[10px] font-bold text-cyan-600 uppercase font-mono">
                                                ENG: {saleFormData.engineNumber || '------'}
                                            </p>
                                        </div>

                                        <div className="p-5 bg-white rounded-3xl border border-slate-200 shadow-sm">
                                            <p className="text-[8px] font-black text-slate-400 uppercase mb-2">Total Contract Volume</p>
                                            <p className="text-3xl font-black text-slate-950 font-mono tracking-tighter">
                                                {formatCurrency(saleFormData.totalPrice || 0)}
                                            </p>
                                        </div>

                                        <div className="p-4 bg-emerald-50 rounded-2xl border border-emerald-100 flex items-center justify-between">
                                            <span className="text-[8px] font-black text-emerald-600 uppercase tracking-widest">Gross Mode</span>
                                            <span className="text-[10px] font-black text-emerald-700 uppercase">{saleFormData.paymentType}</span>
                                        </div>
                                    </div>

                                    <div className="pt-6 space-y-4">
                                        <IntegratedInput label="Internal Administrative Notes" value={saleFormData.notes} onChange={(e: any) => setSaleFormData({...saleFormData, notes: e.target.value})} icon={FileText} placeholder="..." />

                                        <button
                                            onClick={handleSaleSubmit}
                                            disabled={isProcessing || !saleFormData.engineNumber || !saleFormData.customerId || !Number(saleFormData.totalPrice)}
                                            className="w-full bg-slate-950 text-white py-6 rounded-[2rem] font-black uppercase text-xs tracking-[0.2em] shadow-2xl hover:bg-black transition-all flex items-center justify-center gap-3 disabled:opacity-30 disabled:grayscale"
                                        >
                                            {isProcessing ? <Loader2 size={20} className="animate-spin" /> : <BadgeCheck size={20} />}
                                            {isProcessing ? 'Database Synced...' : 'Finalize & Invoice'}
                                        </button>
                                        <button onClick={() => setIsSaleModalOpen(false)} className="w-full text-slate-400 py-2 text-[10px] font-bold uppercase tracking-widest text-center">Abort Checkout</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* MODAL: SALE DETAIL VIEWER (INVOICE PREVIEW) */}
            {viewingSale && (
                <div className="fixed inset-0 bg-slate-950/90 z-[150] flex items-center justify-center p-4 backdrop-blur-2xl overflow-y-auto leading-none">
                    <div className="bg-white rounded-[3rem] w-full max-w-4xl shadow-2xl my-auto animate-fade-in overflow-hidden relative border border-white/20">
                        <div className="absolute top-0 right-0 p-8 no-print z-50">
                            <button onClick={() => setViewingSale(null)} className="p-3 bg-slate-900 text-white rounded-full hover:bg-rose-600 transition-colors shadow-xl"><X size={24}/></button>
                        </div>

                        <div className="p-16 space-y-12">
                            {/* Header Branding */}
                            <div className="flex justify-between items-start border-b-4 border-slate-950 pb-10">
                                <div className="flex items-center gap-6">
                                    <div className="w-20 h-20 bg-slate-950 text-white rounded-[2rem] flex items-center justify-center shadow-2xl"><Bike size={48} /></div>
                                    <div>
                                        <h1 className="text-4xl font-black font-logo text-slate-950 uppercase italic tracking-tighter leading-none">MOTOAPP</h1>
                                        <p className="text-[12px] font-black text-slate-400 uppercase tracking-[0.4em] mt-3">Authorized Sales Invoice</p>
                                    </div>
                                </div>
                                <div className="text-right">
                                    <h2 className="text-2xl font-black text-slate-950 uppercase tracking-tighter italic">Voucher Detail</h2>
                                    <p className="text-[10px] font-black text-cyan-600 uppercase mt-1 font-mono">{viewingSale.id}</p>
                                    <div className={`mt-4 px-4 py-1.5 rounded-full text-[9px] font-black uppercase tracking-[0.2em] border inline-block ${
                                        viewingSale.paymentType === 'Full Payment' ? 'bg-emerald-50 text-emerald-600 border-emerald-100' : 'bg-indigo-50 text-indigo-600 border-indigo-100'
                                    }`}>
                                        {viewingSale.paymentType}
                                    </div>
                                </div>
                            </div>

                            {/* Parties Section */}
                            <div className="grid grid-cols-2 gap-12">
                                <div className="space-y-6">
                                    <div>
                                        <p className="text-[9px] font-black text-slate-400 uppercase tracking-[0.2em] mb-3 flex items-center gap-2"><User size={12}/> Bill To Customer</p>
                                        {/* FIX: Handle customer object in invoice preview */}
                                        <h4 className="text-xl font-black text-slate-950 uppercase">
                                            {typeof viewingSale.customer === 'object' ? viewingSale.customer.name : viewingSale.customer}
                                        </h4>
                                        {(() => {
                                            // Robust customer lookup: try object first, then find by ID
                                            const cust = typeof viewingSale.customer === 'object' ? viewingSale.customer : customers.find((c:any) => c.id === viewingSale.customerId);
                                            return cust ? (
                                                <div className="mt-3 space-y-1">
                                                    <p className="text-[10px] font-bold text-slate-500 uppercase flex items-center gap-2"><Smartphone size={10}/> {cust.contact}</p>
                                                    <p className="text-[10px] font-bold text-slate-500 uppercase flex items-center gap-2"><MapPin size={10}/> {cust.address}</p>
                                                </div>
                                            ) : null;
                                        })()}
                                    </div>
                                </div>
                                <div className="text-right space-y-6">
                                    <div>
                                        <p className="text-[9px] font-black text-slate-400 uppercase tracking-[0.2em] mb-3">Transaction Info</p>
                                        <p className="text-xs font-black text-slate-900 uppercase">Date of Issue: <span className="text-slate-500 font-mono">{viewingSale.date}</span></p>
                                        <p className="text-xs font-black text-slate-900 uppercase mt-2">Sale Ref: <span className="text-slate-500 font-mono">{viewingSale.refNumber || 'N/A'}</span></p>
                                    </div>
                                </div>
                            </div>

                            {/* Product Specs Grid */}
                            <div className="bg-slate-50 rounded-[2.5rem] p-10 border border-slate-100 relative overflow-hidden">
                                <div className="absolute top-0 left-0 w-1 h-full bg-slate-950"></div>
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-8">
                                    <div className="col-span-2">
                                        <p className="text-[8px] font-black text-slate-400 uppercase tracking-widest mb-1.5">Description of Goods</p>
                                        <p className="text-lg font-black text-slate-900 uppercase">{viewingSale.bike}</p>
                                        <p className="text-[10px] font-bold text-cyan-600 uppercase tracking-widest mt-1">{viewingSale.color || 'Standard Variant'}</p>
                                    </div>
                                    <div>
                                        <p className="text-[8px] font-black text-slate-400 uppercase tracking-widest mb-1.5">Engine Serial</p>
                                        <p className="text-xs font-black font-mono text-slate-900 uppercase tracking-wider">{viewingSale.engine}</p>
                                    </div>
                                    <div>
                                        <p className="text-[8px] font-black text-slate-400 uppercase tracking-widest mb-1.5">Chassis Serial</p>
                                        <p className="text-xs font-black font-mono text-slate-900 uppercase tracking-wider">{viewingSale.chassis}</p>
                                    </div>
                                </div>
                            </div>

                            {/* Financial Summary Table */}
                            <div className="space-y-4">
                                <table className="w-full text-left">
                                    <thead className="bg-slate-950 text-white rounded-xl">
                                    <tr className="text-[9px] font-black uppercase tracking-[0.2em]">
                                        <th className="px-6 py-4">Financial Ledger Item</th>
                                        <th className="px-6 py-4 text-right">Debit Volume (PKR)</th>
                                    </tr>
                                    </thead>
                                    <tbody className="divide-y divide-slate-100">
                                    <tr>
                                        <td className="px-6 py-6 text-xs font-bold text-slate-600 uppercase">Net Unit Agreement Total</td>
                                        <td className="px-6 py-6 text-right font-black font-mono text-slate-950 text-lg">{formatCurrency(viewingSale.total)}</td>
                                    </tr>
                                    {viewingSale.paymentType !== 'Full Payment' && (
                                        <tr>
                                            <td className="px-6 py-6">
                                                <p className="text-xs font-bold text-indigo-600 uppercase">Linear Financing Schedule</p>
                                                <p className="text-[9px] text-slate-400 font-bold uppercase mt-1">{viewingSale.installmentsCount} Monthly Installments @ {formatCurrency(viewingSale.monthlyAmount)} / mo</p>
                                            </td>
                                            <td className="px-6 py-6 text-right font-black font-mono text-slate-400">Recovery Tracked</td>
                                        </tr>
                                    )}
                                    </tbody>
                                    <tfoot className="border-t-4 border-slate-950">
                                    <tr className="bg-slate-50">
                                        <td className="px-6 py-6 text-xs font-black text-slate-950 uppercase tracking-widest">Total Invoice Value</td>
                                        <td className="px-6 py-6 text-right font-black font-mono text-2xl text-slate-950">{formatCurrency(viewingSale.total)}</td>
                                    </tr>
                                    </tfoot>
                                </table>
                            </div>

                            {/* Footer / Auth */}
                            <div className="pt-16 flex justify-between items-end">
                                <div className="max-w-xs space-y-4">
                                    <div className="flex items-center gap-3">
                                        <ShieldCheck className="text-emerald-500" size={16}/>
                                        <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Data Verification Hash: {btoa(viewingSale.id).slice(0, 12)}</p>
                                    </div>
                                    <p className="text-[8px] text-slate-400 font-bold uppercase leading-relaxed italic">The above unit is sold in good working condition. Registration responsibility lies with the dealership agent unless specified.</p>
                                </div>
                                <div className="text-center w-48 space-y-3">
                                    <div className="h-[1px] bg-slate-300 w-full mb-3"></div>
                                    <p className="text-[10px] font-black text-slate-950 uppercase tracking-widest">Authorized Signature</p>
                                    <p className="text-[8px] font-bold text-slate-400 uppercase">Sales Executive Official Stamp</p>
                                </div>
                            </div>

                            <div className="pt-12 text-center border-t border-dashed border-slate-200 no-print">
                                <button onClick={() => window.print()} className="px-8 py-4 bg-slate-950 text-white rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] shadow-xl hover:bg-black transition-all flex items-center justify-center gap-3 mx-auto">
                                    <Printer size={16}/> Execute Physical Print
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            <style>{`
        @media print {
            .no-print { display: none !important; }
            body { background: white !important; padding: 0 !important; margin: 0 !important; }
            .bg-slate-950 { background-color: #020617 !important; -webkit-print-color-adjust: exact; }
            .text-white { color: white !important; -webkit-print-color-adjust: exact; }
            .bg-slate-50 { background-color: #f8fafc !important; -webkit-print-color-adjust: exact; }
            .shadow-2xl, .shadow-xl, .shadow-lg { box-shadow: none !important; }
            .rounded-[3rem] { border-radius: 0 !important; }
            .border-white/10 { border-color: transparent !important; }
            @page { size: A4; margin: 2cm; }
        }
      `}</style>
        </div>
    );
}

function ShieldCheck({ size, className }: any) {
    return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className={className}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path><path d="m9 12 2 2 4-4"></path></svg>;
}
