
import React, { useState, useMemo, useEffect } from 'react';
import {
    CalendarDays, HandCoins, Banknote, CheckCircle2, Search, Truck,
    Printer, Pencil, X, Activity, User, Bike, PackageCheck,
    DollarSign, Clock, FileText, UserPlus, Briefcase,
    TrendingUp, BadgeCheck, Binary, Landmark, Hash, Calculator, AlertTriangle
} from 'lucide-react';
import { router } from '@inertiajs/react';
import { IntegratedInput, IntegratedSelect, formatCurrency, getCurrentDate } from './CommonUI.tsx';

export function BookingsPage({
                                 products, customers, accounts, bookings, salesHistory, physicalStock, notify
                             }: any) {

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isDeliveryModalOpen, setIsDeliveryModalOpen] = useState(false);
    const [viewingReceipt, setViewingReceipt] = useState<any>(null);
    const [editingId, setEditingId] = useState<string | null>(null);
    const [deliveringBooking, setDeliveringBooking] = useState<any>(null);
    const [searchTerm, setSearchTerm] = useState('');

    const [formData, setFormData] = useState({
        date: getCurrentDate(),
        promisedDate: getCurrentDate(),
        customerId: '',
        productId: '',
        totalPrice: '',
        advanceAmount: '',
        accountId: accounts?.[0]?.id || '', // Default to first account
        status: 'Pending',
        notes: '',
        refNumber: ''
    });

    const [deliveryFormData, setDeliveryFormData] = useState({
        date: getCurrentDate(),
        engineNumber: '',
        chassisNumber: '',
        paymentType: 'Full Payment',
        additionalDownPayment: '0',
        installmentsCount: '12',
        monthlyAmount: '',
        accountId: '',
        notes: '',
        refNumber: ''
    });

    // Ensure account defaults are set when modal opens or accounts load
    useEffect(() => {
        if (accounts && accounts.length > 0 && !formData.accountId) {
            setFormData(prev => ({ ...prev, accountId: accounts[0].id }));
        }
        if (accounts && accounts.length > 0 && !deliveryFormData.accountId) {
            setDeliveryFormData(prev => ({ ...prev, accountId: accounts[0].id }));
        }
    }, [accounts, isDeliveryModalOpen, isModalOpen]);

    // --- Data Normalization ---
    const normalizedBookings = useMemo(() => {
        return (bookings || []).map((b: any) => {
            const prodId = b.productId || b.product_id;
            const custId = b.customerId || b.customer_id;

            const product = products.find((p: any) => String(p.id) === String(prodId));
            const customer = customers.find((c: any) => String(c.id) === String(custId));

            return {
                ...b,
                id: b.id,
                productId: prodId,
                customerId: custId,
                productName: product ? `${product.make} ${product.model} (${product.color})` : 'Unknown Unit',
                customerName: customer ? customer.name : 'Unknown Client',
                total: Number(b.total || b.total_amount || 0),
                advance: Number(b.advance || b.advance_amount || 0),
                status: b.status || 'Pending'
            };
        });
    }, [bookings, products, customers]);

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

    // Pre-calculate stock counts for quick lookup in the list view
    const stockCounts = useMemo(() => {
        const counts: Record<string, number> = {};
        (physicalStock || []).forEach((u: any) => {
            // Only count units that are actually In Stock
            if (u.status === 'In Stock' || !u.status) {
                const pid = String(u.productId || u.product_id);
                counts[pid] = (counts[pid] || 0) + 1;
            }
        });
        return counts;
    }, [physicalStock]);

    const availableUnitsForDeliveringProduct = useMemo(() => {
        if (!deliveringBooking) return [];

        const targetProdId = String(deliveringBooking.productId);

        // Map units to use engineNumber as ID so IntegratedSelect returns the string, not the DB ID
        return (physicalStock || [])
            .filter((unit: any) => {
                const unitProdId = String(unit.productId || unit.product_id);
                const isAvailable = unit.status === 'In Stock' || !unit.status; // Robust check
                return unitProdId === targetProdId && isAvailable;
            })
            .map((u: any) => ({
                ...u,
                id: u.engineNumber, // CRITICAL FIX: Override ID with Engine Number for backend validation compatibility
                originalId: u.id
            }));
    }, [physicalStock, deliveringBooking]);

    const filteredBookings = useMemo(() => {
        if (!searchTerm) return normalizedBookings;
        const lower = searchTerm.toLowerCase();
        return normalizedBookings.filter((b: any) =>
            String(b.customerName).toLowerCase().includes(lower) ||
            String(b.id).toLowerCase().includes(lower) ||
            (b.refNumber && String(b.refNumber).toLowerCase().includes(lower)) ||
            String(b.productName).toLowerCase().includes(lower)
        );
    }, [normalizedBookings, searchTerm]);

    // --- Enhanced Financial Calculation ---
    const fulfillmentSummary = useMemo(() => {
        if (!deliveringBooking) return { advance: 0, settlement: 0, totalDown: 0, balance: 0, monthly: 0, totalPrice: 0 };

        const advance = deliveringBooking.advance || 0;
        const settlement = parseFloat(deliveryFormData.additionalDownPayment) || 0;
        const totalDown = advance + settlement;
        const totalPrice = deliveringBooking.total || 0;
        const balance = Math.max(0, totalPrice - totalDown);

        let monthly = 0;
        if (deliveryFormData.paymentType !== 'Full Payment') {
            const months = parseInt(deliveryFormData.installmentsCount) || 1;
            monthly = Math.round(balance / months);
        }

        return { advance, settlement, totalDown, balance, monthly, totalPrice };
    }, [deliveringBooking, deliveryFormData.additionalDownPayment, deliveryFormData.installmentsCount, deliveryFormData.paymentType]);

    const bookingStats = useMemo(() => {
        const active = normalizedBookings.filter((b: any) => b.status === 'Pending' || b.status === 'Confirmed');
        // Only calculate totalAdvance for ACTIVE bookings.
        // Once fulfilled, the advance becomes Sales Revenue and leaves "Booking Capital".
        const totalAdvance = active.reduce((acc: number, b: any) => acc + (Number(b.advance) || 0), 0);
        const fulfilledCount = normalizedBookings.filter((b: any) => b.status === 'Fulfilled').length;

        // Urgent: Promised date is today or in the past
        const today = getCurrentDate();
        const urgentCount = active.filter((b: any) => b.promisedDate && b.promisedDate <= today).length;

        return { activeCount: active.length, totalAdvance, fulfilledCount, urgentCount };
    }, [normalizedBookings]);

    const handleSaveBooking = () => {
        const { customerId, productId } = formData;
        if (!customerId || !productId) return;

        const url = editingId ? `/bookings/${editingId}` : '/bookings';
        const data = editingId ? { ...formData, id: editingId } : formData;

        router.post(url, data, {
            onSuccess: () => {
                setIsModalOpen(false);
                setEditingId(null);
                // Reset but keep default account
                setFormData({
                    date: getCurrentDate(), promisedDate: getCurrentDate(), customerId: '', productId: '',
                    totalPrice: '', advanceAmount: '', accountId: accounts?.[0]?.id || '', status: 'Pending', notes: '', refNumber: ''
                });
                notify(editingId ? 'Booking Updated' : 'Reservation Created');
            }
        });
    };

    const processDelivery = () => {
        const { engineNumber } = deliveryFormData;
        if (!engineNumber || !deliveringBooking) return;

        // Send strictly formatted payload to backend
        const payload = {
            bookingId: deliveringBooking.id,
            // Delivery Details
            engineNumber: deliveryFormData.engineNumber,
            chassisNumber: deliveryFormData.chassisNumber,
            date: deliveryFormData.date,
            accountId: deliveryFormData.accountId,
            notes: deliveryFormData.notes,

            // Financials
            paymentType: deliveryFormData.paymentType,
            totalPrice: fulfillmentSummary.totalPrice,

            bookingAdvance: fulfillmentSummary.advance,
            settlementAmount: fulfillmentSummary.settlement,
            totalDownPayment: fulfillmentSummary.totalDown,

            // Lease Specifics
            installmentsCount: deliveryFormData.installmentsCount,
            monthlyAmount: fulfillmentSummary.monthly
        };

        router.post('/bookings/fulfill', payload, {
            onSuccess: () => {
                setIsDeliveryModalOpen(false);
                setDeliveringBooking(null);
                notify('Booking Fulfilled & Sale Generated');
            }
        });
    };

    return (
        <div className="animate-fade-in space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 px-4 lg:px-0">
                {/* Card 1: Active Reservations (Hero) */}
                <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"><CalendarDays size={80}/></div>
                    <div>
                        <p className="text-[10px] font-black text-cyan-400 uppercase tracking-widest mb-1">Active Reservations</p>
                        <h3 className="text-2xl font-black font-mono tracking-tight">{bookingStats.activeCount} <span className="text-sm text-slate-500 font-bold">Files</span></h3>
                    </div>
                    <div className="flex items-center gap-2 mt-4 text-[9px] font-bold text-slate-400 uppercase">
                        <Clock size={12}/> {bookingStats.urgentCount} Due for Delivery
                    </div>
                </div>

                {/* Card 2: Booking Capital */}
                <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-emerald-50 text-emerald-600 rounded-xl flex items-center justify-center shadow-inner shrink-0"><HandCoins size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Booking Capital</p>
                        <p className="text-xl font-black text-slate-900 font-mono">{formatCurrency(bookingStats.totalAdvance)}</p>
                        <p className="text-[8px] font-bold text-emerald-500 uppercase">Held in Deposit</p>
                    </div>
                </div>

                {/* Card 3: Delivered */}
                <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 shrink-0"><CheckCircle2 size={24}/></div>
                    <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Units Delivered</p>
                        <p className="text-xl font-black text-slate-900 font-mono">{bookingStats.fulfilledCount}</p>
                        <p className="text-[8px] font-bold text-blue-500 uppercase">Successful Handovers</p>
                    </div>
                </div>

                {/* Card 4: Action / New Booking */}
                <div className="bg-gradient-to-br from-cyan-500 to-blue-600 rounded-[2rem] p-6 text-white shadow-lg flex flex-col justify-center items-center text-center cursor-pointer hover:shadow-cyan-500/30 transition-all active:scale-95" onClick={() => { setEditingId(null); setFormData({ ...formData, customerId: '', productId: '', advanceAmount: '', totalPrice: '', notes: '', refNumber: '' }); setIsModalOpen(true); }}>
                    <div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center mb-2"><UserPlus size={20}/></div>
                    <p className="text-[10px] font-black uppercase tracking-widest">New Reservation</p>
                </div>
            </div>

            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 px-4 lg:px-0">
                <div><h3 className="text-lg font-bold font-heading text-slate-900 uppercase italic">Customer Bookings</h3><p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest mt-1">Inventory Lock System</p></div>
                {/* Hidden button, functionality moved to summary card */}
            </div>

            <div className="px-4 lg:px-0 no-print">
                <div className="bg-white rounded-2xl border border-slate-200 flex items-center px-5 py-3 focus-within:border-cyan-500 transition-all shadow-sm">
                    <Search size={18} className="text-slate-400 mr-4" />
                    <input type="text" placeholder="Search by Customer, Booking ID, Bike Model or Ref..." className="bg-transparent border-none outline-none text-[11px] font-black w-full text-slate-900 uppercase tracking-widest placeholder:text-slate-300" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
                </div>
            </div>

            <div className="bg-white rounded-3xl border border-slate-200 overflow-hidden shadow-sm mx-4 lg:mx-0">
                <div className="overflow-x-auto">
                    <table className="w-full text-left">
                        <thead className="bg-slate-50 border-b border-slate-100 shadow-sm"><tr className="text-[10px] font-bold text-slate-400 uppercase tracking-widest italic"><th className="px-6 py-5">Booking Details</th><th className="px-6 py-5 text-center">Status</th><th className="px-6 py-5 text-center">Timeline</th><th className="px-6 py-5 text-center">Deposit</th><th className="px-6 py-5 text-right">Workflow</th></tr></thead>
                        <tbody className="divide-y divide-slate-100">
                        {filteredBookings.map((b: any) => {
                            const availStock = stockCounts[String(b.productId)] || 0;
                            return (
                                <tr key={b.id} className="hover:bg-slate-50/50 transition-colors group">
                                    <td className="px-6 py-5">
                                        <div className="flex items-center gap-3">
                                            <div className="w-10 h-10 rounded-full bg-slate-100 flex items-center justify-center text-slate-500"><Briefcase size={18} /></div>
                                            <div>
                                                <p className="font-bold text-slate-900 text-sm uppercase">{b.customerName}</p>
                                                <p className="text-[10px] text-cyan-600 font-black uppercase mt-1">REF: {b.id} • {b.productName}</p>
                                                {b.status !== 'Fulfilled' && (
                                                    <div className={`mt-1 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[7px] font-black uppercase tracking-wider border ${availStock > 0 ? 'bg-emerald-50 text-emerald-600 border-emerald-100' : 'bg-rose-50 text-rose-600 border-rose-100'}`}>
                                                        {availStock > 0 ? <CheckCircle2 size={8}/> : <AlertTriangle size={8}/>} {availStock} Units Available
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-6 py-5 text-center"><span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[8px] font-black uppercase border tracking-widest ${b.status === 'Fulfilled' ? 'bg-emerald-50 text-emerald-600 border-emerald-100' : b.status === 'Cancelled' ? 'bg-rose-50 text-rose-600 border-rose-100' : 'bg-amber-50 text-amber-600 border-amber-100'}`}>{b.status}</span></td>
                                    <td className="px-6 py-5 text-center"><p className="text-[10px] font-bold text-slate-400 uppercase">Issue: {b.date}</p><p className="text-[10px] font-black text-slate-800 uppercase mt-1">Due: {b.promisedDate || '---'}</p></td>
                                    <td className="px-6 py-5 text-center"><p className="font-black text-slate-900 text-sm font-mono">{formatCurrency(b.advance)}</p><p className="text-[8px] font-bold text-slate-400 uppercase">of {formatCurrency(b.total)}</p></td>
                                    <td className="px-6 py-5 text-right"><div className="flex justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">{(b.status === 'Pending' || b.status === 'Confirmed') && (<button onClick={() => { setDeliveringBooking(b); setDeliveryFormData({...deliveryFormData, notes: b.notes || '', refNumber: '', additionalDownPayment: '0', accountId: accounts?.[0]?.id || '' }); setIsDeliveryModalOpen(true); }} className="p-2 text-white bg-slate-900 hover:bg-emerald-600 rounded-xl transition-all shadow-md"><Truck size={14}/></button>)}<button onClick={() => setViewingReceipt(b)} className="p-2 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-xl transition-all"><Printer size={14}/></button><button onClick={() => { setEditingId(b.id); setFormData({ ...b, totalPrice: b.total.toString(), advanceAmount: b.advance.toString(), refNumber: b.refNumber || '', accountId: b.accountId || accounts?.[0]?.id || '' }); setIsModalOpen(true); }} className="p-2 text-slate-400 hover:text-cyan-600 hover:bg-cyan-50 rounded-xl transition-all"><Pencil size={14}/></button></div></td>
                                </tr>
                            );
                        })}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* CREATE/EDIT BOOKING MODAL */}
            {isModalOpen && (
                <div className="fixed inset-0 bg-slate-900/70 z-[100] flex items-center justify-center p-4 backdrop-blur-sm overflow-y-auto">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-4xl shadow-2xl border border-white/20 my-auto overflow-hidden animate-fade-in">
                        <div className="bg-slate-950 p-8 flex justify-between items-center text-white">
                            <div className="flex items-center gap-4"><div className="w-12 h-12 bg-cyan-500 rounded-2xl flex items-center justify-center text-slate-950 shadow-lg"><CalendarDays size={24} /></div><div><h3 className="font-bold text-sm uppercase tracking-[0.3em] italic font-heading">{editingId ? 'Update Booking' : 'New Booking'}</h3></div></div><button onClick={() => setIsModalOpen(false)} className="bg-white/5 p-2 rounded-full hover:bg-white/10"><X size={20}/></button>
                        </div>
                        <div className="p-10 space-y-8">
                            <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
                                <div className="md:col-span-2"><IntegratedSelect label="Customer" value={formData.customerId} onChange={(e: any) => setFormData({...formData, customerId: e.target.value})} options={customers} displayKey="name" icon={User} /></div>
                                <IntegratedInput label="Date" type="date" value={formData.date} onChange={(e: any) => setFormData({...formData, date: e.target.value})} icon={CalendarDays} />
                                <IntegratedInput label="Ref #" value={formData.refNumber} onChange={(e: any) => setFormData({...formData, refNumber: e.target.value})} icon={Hash} />
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 p-6 bg-slate-50 rounded-3xl border border-slate-100">
                                <div className="md:col-span-2"><IntegratedSelect label="Product" value={formData.productId} onChange={(e: any) => { const p = products.find((prod: any) => prod.id === e.target.value); setFormData({...formData, productId: e.target.value, totalPrice: p ? p.price.toString() : ''}); }} options={formattedProducts} displayKey="label" icon={Bike} /></div>
                                <IntegratedSelect label="Status" value={formData.status} onChange={(e: any) => setFormData({...formData, status: e.target.value})} options={['Pending', 'Confirmed', 'Cancelled']} icon={Activity} />
                                <IntegratedInput label="Target Delivery" type="date" value={formData.promisedDate} onChange={(e: any) => setFormData({...formData, promisedDate: e.target.value})} icon={Clock} />
                            </div>

                            {/* Enhanced Financial Section with Account Selector */}
                            <div className="p-8 bg-cyan-50/30 rounded-[2.5rem] border-2 border-cyan-100 space-y-4">
                                <h4 className="text-[10px] font-black text-cyan-600 uppercase tracking-widest flex items-center gap-2"><DollarSign size={14}/> Financial Commitment</h4>
                                <div className="grid grid-cols-1 md:grid-cols-4 gap-6 items-end">
                                    <IntegratedInput label="Agreed Price" value={formData.totalPrice} onChange={(e: any) => setFormData({...formData, totalPrice: e.target.value})} icon={DollarSign} />
                                    <IntegratedInput label="Advance Cash" value={formData.advanceAmount} onChange={(e: any) => setFormData({...formData, advanceAmount: e.target.value})} icon={Banknote} />
                                    <IntegratedSelect label="Deposit Account" value={formData.accountId} onChange={(e: any) => setFormData({...formData, accountId: e.target.value})} options={accounts} displayKey="name" icon={Landmark} />
                                    <div className="bg-white p-3 rounded-xl border border-cyan-100 flex flex-col justify-center shadow-sm h-[60px]">
                                        <p className="text-[8px] font-black uppercase text-slate-400 tracking-widest mb-1">Balance Due</p>
                                        <p className="text-lg font-black font-mono tracking-tight text-rose-600">{formatCurrency((parseFloat(formData.totalPrice) || 0) - (parseFloat(formData.advanceAmount) || 0))}</p>
                                    </div>
                                </div>
                            </div>

                            <IntegratedInput label="Notes" value={formData.notes} onChange={(e: any) => setFormData({...formData, notes: e.target.value})} icon={FileText} />
                            <button onClick={handleSaveBooking} className="w-full bg-slate-900 text-white py-6 rounded-3xl font-black uppercase text-xs tracking-[0.2em] shadow-xl hover:bg-black transition-all flex items-center justify-center gap-3"><BadgeCheck size={20} /> {editingId ? 'Save Changes' : 'Finalize Booking'}</button>
                        </div>
                    </div>
                </div>
            )}

            {/* DELIVERY / FULFILLMENT MODAL */}
            {isDeliveryModalOpen && deliveringBooking && (
                <div className="fixed inset-0 bg-slate-900/80 z-[120] flex items-center justify-center p-4 backdrop-blur-sm overflow-y-auto leading-none">
                    <div className="bg-white rounded-[2.5rem] w-full max-w-5xl shadow-2xl border border-white/20 my-auto overflow-hidden animate-fade-in leading-none">
                        <div className="bg-emerald-950 p-8 flex justify-between items-center text-white leading-none">
                            <div className="flex items-center gap-4 leading-none"><div className="w-12 h-12 bg-emerald-500 rounded-2xl flex items-center justify-center text-emerald-950 shadow-lg leading-none"><Truck size={24} /></div><div className="leading-none"><h3 className="font-bold text-sm uppercase tracking-[0.3em] italic font-heading leading-none">Fulfillment & Invoicing</h3></div></div>
                            <button onClick={() => setIsDeliveryModalOpen(false)} className="bg-white/5 p-2 rounded-full hover:bg-white/10 transition-colors leading-none"><X size={20}/></button>
                        </div>

                        <div className="p-10 grid grid-cols-1 lg:grid-cols-3 gap-8">
                            {/* Left Column: Unit Selection */}
                            <div className="lg:col-span-2 space-y-8">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 leading-none">
                                    <div className="md:col-span-2 leading-none">
                                        <IntegratedSelect
                                            label="Assign Stock Unit"
                                            value={deliveryFormData.engineNumber}
                                            onChange={(e: any) => { const unit = availableUnitsForDeliveringProduct.find((u: any) => u.engineNumber === e.target.value); setDeliveryFormData({...deliveryFormData, engineNumber: e.target.value, chassisNumber: unit?.chassisNumber || ''}); }}
                                            options={availableUnitsForDeliveringProduct}
                                            displayKey="engineNumber"
                                            icon={PackageCheck}
                                            placeholder={availableUnitsForDeliveringProduct.length > 0 ? "Select Engine Number..." : "⚠️ No Units of this Model Available"}
                                        />
                                        {availableUnitsForDeliveringProduct.length === 0 && (
                                            <p className="text-[10px] text-rose-500 font-bold uppercase mt-2 ml-1 flex items-center gap-1"><AlertTriangle size={12}/> Stock Empty for this Model. Add stock first.</p>
                                        )}
                                    </div>
                                    <IntegratedInput label="Chassis ID (Verified)" value={deliveryFormData.chassisNumber} disabled icon={Binary} />
                                    <IntegratedInput label="Sale Date" type="date" value={deliveryFormData.date} onChange={(e: any) => setDeliveryFormData({...deliveryFormData, date: e.target.value})} icon={CalendarDays} />
                                </div>

                                <div className="p-6 bg-slate-50 rounded-3xl border border-slate-100 space-y-5">
                                    <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200 pb-2">Financial Settlement</h4>
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <IntegratedSelect label="Final Payment Mode" value={deliveryFormData.paymentType} onChange={(e: any) => setDeliveryFormData({...deliveryFormData, paymentType: e.target.value})} options={['Full Payment', 'Lease/Installments']} icon={Activity} />
                                        <IntegratedSelect label="Deposit Account" value={deliveryFormData.accountId} onChange={(e: any) => setDeliveryFormData({...deliveryFormData, accountId: e.target.value})} options={accounts} displayKey="name" icon={Landmark} />
                                    </div>

                                    <div className={`transition-all duration-300 ${deliveryFormData.paymentType !== 'Full Payment' ? 'block' : 'hidden'}`}>
                                        <div className="grid grid-cols-2 gap-6">
                                            <IntegratedInput label="Duration (Months)" type="number" value={deliveryFormData.installmentsCount} onChange={(e: any) => setDeliveryFormData({...deliveryFormData, installmentsCount: e.target.value})} icon={Clock} />
                                            <div className="flex flex-col justify-end">
                                                <p className="text-[8px] font-black text-slate-400 uppercase mb-1.5 ml-1">Monthly Installment</p>
                                                <div className="h-10 px-3 flex items-center bg-white border border-slate-200 rounded-lg text-sm font-black font-mono text-indigo-600">{formatCurrency(fulfillmentSummary.monthly)}</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Right Column: Financial Breakdown */}
                            <div className="space-y-6">
                                <div className="bg-emerald-50/50 border-2 border-emerald-100 rounded-[2.5rem] p-6 space-y-4 shadow-sm">
                                    <h4 className="text-[10px] font-black text-emerald-800 uppercase tracking-widest flex items-center gap-2"><Calculator size={14}/> Financial Breakdown</h4>

                                    <div className="space-y-3">
                                        <div className="flex justify-between items-center">
                                            <span className="text-[10px] font-bold text-emerald-600 uppercase">Unit Price</span>
                                            <span className="text-sm font-black font-mono text-emerald-900">{formatCurrency(fulfillmentSummary.totalPrice)}</span>
                                        </div>
                                        <div className="w-full h-px bg-emerald-200/50"></div>

                                        <div className="flex justify-between items-center">
                                            <span className="text-[10px] font-bold text-slate-500 uppercase">Booking Advance</span>
                                            <span className="text-xs font-bold font-mono text-slate-700">{formatCurrency(fulfillmentSummary.advance)}</span>
                                        </div>

                                        <div className="bg-white p-3 rounded-xl border border-emerald-100">
                                            <IntegratedInput
                                                label="Settlement Amount (Pay Now)"
                                                value={deliveryFormData.additionalDownPayment}
                                                onChange={(e: any) => setDeliveryFormData({...deliveryFormData, additionalDownPayment: e.target.value})}
                                                icon={Banknote}
                                            />
                                        </div>

                                        <div className="flex justify-between items-center pt-2">
                                            <span className="text-[10px] font-black text-emerald-700 uppercase tracking-tight">Total Down Payment</span>
                                            <span className="text-sm font-black font-mono text-emerald-800 border-b-2 border-emerald-200">{formatCurrency(fulfillmentSummary.totalDown)}</span>
                                        </div>
                                    </div>
                                </div>

                                <div className="bg-slate-900 text-white p-6 rounded-[2.5rem] shadow-xl text-center">
                                    <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest mb-1">Net Balance / Financed</p>
                                    <p className="text-3xl font-black font-mono tracking-tight text-white">{formatCurrency(fulfillmentSummary.balance)}</p>
                                </div>

                                <button onClick={processDelivery} disabled={!deliveryFormData.engineNumber || (fulfillmentSummary.settlement > 0 && !deliveryFormData.accountId)} className="w-full bg-emerald-600 text-white py-5 rounded-3xl font-black uppercase text-xs tracking-[0.2em] shadow-xl hover:bg-emerald-700 transition-all flex items-center justify-center gap-3 disabled:opacity-50 disabled:grayscale leading-none">
                                    <PackageCheck size={18} /> Confirm Handover
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
