// Import React cores and library hooks for state, effect, routing and icons
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
    FileText, User, Car, Calendar, CreditCard, Wallet, 
    ArrowLeft, CheckCircle, AlertTriangle, Info, Printer, X
} from 'lucide-react';
import api from '../api';

const FinalSummary = ({ bookingId, onClose }) => {
    // Component state configurations to track loaded models, input amounts, and spinner overlays
    const { id: routeId } = useParams();
    const id = bookingId || routeId;
    const navigate = useNavigate();
    const [booking, setBooking] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [collectAmt, setCollectAmt] = useState('');

    // Effect lifecycle monitor to pull booking data whenever the ID parameter resolves
    useEffect(() => {
        loadBooking();
    }, [id]);

    // Backend endpoint connection routine to fetch specific booking row records
    const loadBooking = async () => {
        try {
            setLoading(true);
            const res = await api.get(`/bookings/${id}`);
            setBooking(res.data);
            setError('');
        } catch (err) {
            console.error(err);
            setError('Failed to load booking details.');
        } finally {
            setLoading(false);
        }
    };

    // Parser block mapping payment JSON arrays stored in database tables
    let dbPaymentHistory = [];
    try {
        if (booking && booking.payment_history) {
            dbPaymentHistory = JSON.parse(booking.payment_history);
        }
    } catch (e) {
        console.error("Failed to parse payment history:", e);
    }
    const advancePaid = parseFloat(booking?.advance_paid) || 0;
    let displayPaymentHistory = [...dbPaymentHistory];

    // Prepend Advance Payment if not already present in the database logs
    const hasAdvanceInDb = dbPaymentHistory.some(item => item.type === 'Advance');
    if (advancePaid > 0 && !hasAdvanceInDb) {
        displayPaymentHistory.unshift({
            date: booking?.booking_date || booking?.created_at || new Date().toISOString(),
            type: 'Advance',
            description: 'Advance Payment',
            amount: advancePaid,
            mode: booking?.payment_method || 'Cash'
        });
    }

    // Prepend Security Deposit so it is at the very top
    if (booking && parseFloat(booking.deposit) > 0) {
        displayPaymentHistory.unshift({
            date: booking.booking_date || booking.created_at || new Date().toISOString(),
            type: 'Deposit',
            description: 'Security Deposit (Refundable)',
            amount: parseFloat(booking.deposit),
            mode: booking.payment_method || 'Cash'
        });
    }

    const handleMarkAsPaid = async () => {
        const remaining = totalAmount - totalPaid;
        if (remaining <= 0) {
            alert('Booking is already fully paid.');
            return;
        }

        const newHistory = [...dbPaymentHistory, {
            date: new Date().toISOString(),
            type: 'Final',
            description: 'Settlement Payment',
            amount: remaining,
            mode: booking.payment_method || 'Cash'
        }];

        try {
            await api.patch(`/bookings/${booking.booking_id || booking.id}/payment`, {
                payment_status: 'Paid',
                payment_date: new Date().toISOString(),
                amount_collected: totalAmount,
                payment_history: JSON.stringify(newHistory)
            });
            loadBooking();
        } catch (err) {
            console.error(err);
            alert('Failed to update payment status.');
        }
    };

    const handleCollectPayment = async () => {
        const amt = parseFloat(collectAmt);
        if (isNaN(amt) || amt <= 0) {
            alert('Please enter a valid amount.');
            return;
        }
        
        const newTotalPaid = totalPaid + amt;
        const targetPaymentStatus = newTotalPaid >= totalAmount ? 'Paid' : 'Partially Paid';

        const newHistory = [...dbPaymentHistory, {
            date: new Date().toISOString(),
            type: targetPaymentStatus === 'Paid' ? 'Final' : 'Partial',
            description: targetPaymentStatus === 'Paid' ? 'Settlement Payment' : 'Partial Payment',
            amount: amt,
            mode: booking.payment_method || 'Cash'
        }];

        try {
            await api.patch(`/bookings/${booking.booking_id || booking.id}/payment`, {
                payment_status: targetPaymentStatus,
                payment_date: new Date().toISOString(),
                amount_collected: newTotalPaid,
                payment_history: JSON.stringify(newHistory)
            });
            setCollectAmt('');
            loadBooking();
        } catch (err) {
            console.error(err);
            alert('Failed to record payment.');
        }
    };

    if (loading) {
        return (
            <div className="d-flex justify-content-center align-items-center" style={{ minHeight: '80vh', color: '#3b82f6' }}>
                <div className="spinner-border" role="status">
                    <span className="visually-hidden">Loading...</span>
                </div>
            </div>
        );
    }

    if (error || !booking) {
        return (
            <div className="container py-4" style={{ minHeight: '85vh', background: '#1f222e' }}>
                <div className="alert alert-danger" role="alert">
                    {error || 'Booking not found.'}
                </div>
                <button className="btn btn-primary" onClick={() => navigate('/bookings')}>
                    <ArrowLeft size={16} className="me-2" /> Back to Bookings
                </button>
            </div>
        );
    }

    // Calculations
    const basePrice = parseFloat(booking.base_price) || 0;
    const discountAmt = parseFloat(booking.discount_amount) || 0;
    const taxAmt = parseFloat(booking.tax_amount) || 0;
    const totalAmount = parseFloat(booking.total_price) || 0;
    const securityDeposit = parseFloat(booking.deposit) || 0;
    // Status Logic
    const isPaid = booking.payment_status === 'Paid';
    const isPartiallyPaid = booking.payment_status === 'Partially Paid';
    
    const amountCollected = parseFloat(booking.amount_collected) || advancePaid;
    const totalPaid = amountCollected;
    const remainingAmountDue = Math.max(0, totalAmount - totalPaid);

    const fmtAED = (v) => `AED ${Number(v).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    const formatDateStr = (d) => d ? new Date(d).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', hour12: true }) : '—';

    // Calculate Days
    const startDate = new Date(booking.start_date);
    const endDate = new Date(booking.end_date);
    const daysCount = Math.max(1, Math.round((endDate - startDate) / 86400000)) || 1;

    return (
        <div style={{ background: 'radial-gradient(circle at top, rgba(168, 85, 247, 0.15), transparent 60%), #0f172a', minHeight: '100vh', color: '#f8fafc', padding: '24px' }}>
            {/* Header section */}
            <div className="d-flex align-items-center justify-content-between mb-4">
                <div className="d-flex align-items-center gap-3">
                    {!onClose && (
                        <button 
                            onClick={() => navigate(`/AddBooking?id=${booking.booking_id || booking.id}`)}
                            className="btn d-flex align-items-center justify-content-center"
                            style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid #323746', color: '#cbd5e1', padding: '8px 12px', borderRadius: '8px' }}
                        >
                            <ArrowLeft size={16} />
                        </button>
                    )}
                    <div>
                        <h2 style={{ fontSize: '20px', fontWeight: 'bold', margin: 0, textTransform: 'uppercase', letterSpacing: '0.5px' }}>Final Summary & Payment</h2>
                        <div className="d-flex align-items-center gap-2 mt-1" style={{ fontSize: '12px', color: booking.status === 'cancelled' ? '#ef4444' : '#22c55e', fontWeight: '600' }}>
                            {booking.status === 'cancelled' ? <X size={14} /> : <CheckCircle size={14} />}
                            {booking.status === 'cancelled' ? 'Trip Cancelled' : 'Trip Completed'}
                        </div>
                    </div>
                </div>
                {onClose && (
                    <button 
                        onClick={onClose}
                        className="btn d-flex align-items-center justify-content-center"
                        style={{ background: 'rgba(255, 255, 255, 0.05)', border: '1px solid rgba(255, 255, 255, 0.1)', color: '#94a3b8', padding: '8px 12px', borderRadius: '8px', transition: 'all 0.2s' }}
                        onMouseOver={(e) => { e.currentTarget.style.background = 'rgba(239, 68, 68, 0.1)'; e.currentTarget.style.color = '#ef4444'; e.currentTarget.style.borderColor = 'rgba(239, 68, 68, 0.3)'; }}
                        onMouseOut={(e) => { e.currentTarget.style.background = 'rgba(255, 255, 255, 0.05)'; e.currentTarget.style.color = '#94a3b8'; e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.1)'; }}
                    >
                        <X size={18} /> Close
                    </button>
                )}
            </div>


            {/* Warning Alert Bar */}
            {!isPaid ? (
                <div className="p-3 mb-4 rounded-3 d-flex align-items-center gap-2" style={{ background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)' }}>
                    <AlertTriangle color="#ef4444" size={18} />
                    <span style={{ fontSize: '13px', color: '#fca5a5' }}>
                        {booking.status === 'cancelled' 
                            ? "This trip is cancelled but the payment is not yet settled. Please collect or refund the pending amount."
                            : "This trip is completed but the payment is not yet settled. Please collect the remaining amount from the customer."
                        }
                    </span>
                </div>
            ) : (
                <div className="p-3 mb-4 rounded-3 d-flex align-items-center gap-2" style={{ background: 'rgba(34,197,94,0.08)', border: '1px solid rgba(34,197,94,0.2)' }}>
                    <CheckCircle color="#22c55e" size={18} />
                    <span style={{ fontSize: '13px', color: '#86efac' }}>
                        {booking.status === 'cancelled'
                            ? "This booking is cancelled and fully settled."
                            : "This booking has been fully settled. No further actions are required."
                        }
                    </span>
                </div>
            )}

            {/* Grid for billing summaries */}
            {booking.status === 'cancelled' ? (
                <div className="row g-4 mb-4">
                    <div className="col-lg-6 mx-auto">
                        <div className="p-4 rounded-3" style={{ background: '#272b38', border: '1px solid #323746' }}>
                            <h5 className="fw-bold mb-3" style={{ fontSize: '13px', textTransform: 'uppercase', letterSpacing: '0.5px', color: '#22c55e' }}>Payments Collected</h5>
                            <div className="d-flex justify-content-between mb-2" style={{ fontSize: '12.5px', color: '#cbd5e1' }}>
                                <span>Advance Paid</span>
                                <span>{fmtAED(advancePaid)}</span>
                            </div>
                            <div className="d-flex justify-content-between pt-2 border-top border-secondary mb-4">
                                <span style={{ fontSize: '12px', fontWeight: 'bold', color: '#94a3b8' }}>TOTAL RENTAL PAID</span>
                                <span style={{ fontSize: '16px', fontWeight: 'bold', color: '#22c55e' }}>{fmtAED(advancePaid)}</span>
                            </div>

                            <h5 className="fw-bold mb-3" style={{ fontSize: '13px', textTransform: 'uppercase', letterSpacing: '0.5px', color: '#eab308' }}>Security Deposit (Refundable)</h5>
                            <div className="d-flex justify-content-between mb-3" style={{ fontSize: '12.5px', color: '#cbd5e1' }}>
                                <span>Security Deposit Collected</span>
                                <span style={{ color: '#eab308', fontWeight: 'bold' }}>{fmtAED(securityDeposit)}</span>
                            </div>
                        </div>
                    </div>
                </div>
            ) : (
                <div className="row g-4 mb-4">
                    {/* 1. Rental Bill Summary */}
                    <div className="col-lg-4">
                        <div className="p-4 rounded-4" style={{ background: 'rgba(30, 41, 59, 0.5)', border: '1px solid rgba(168, 85, 247, 0.15)', backdropFilter: 'blur(10px)', height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', boxShadow: '0 4px 20px rgba(0, 0, 0, 0.2)' }}>
                            <div>
                                <h5 className="fw-bold mb-3 d-flex align-items-center gap-2" style={{ fontSize: '13px', textTransform: 'uppercase', letterSpacing: '0.5px', color: '#a855f7' }}>
                                    <FileText size={16} /> Rental Bill Summary
                                </h5>
                                <div className="d-flex justify-content-between mb-2" style={{ fontSize: '12.5px', color: '#cbd5e1' }}>
                                    <span>Base Price ({fmtAED(basePrice)} x {daysCount} Days)</span>
                                    <span>{fmtAED(basePrice * daysCount)}</span>
                                </div>
                                <div className="d-flex justify-content-between mb-2" style={{ fontSize: '12.5px', color: '#cbd5e1' }}>
                                    <span>Discount</span>
                                    <span style={{ color: '#22c55e' }}>-{fmtAED(discountAmt)}</span>
                                </div>
                                <div className="d-flex justify-content-between mb-3" style={{ fontSize: '12.5px', color: '#cbd5e1' }}>
                                    <span>Tax ({booking.tax_amount || 5}%)</span>
                                    <span>{fmtAED(taxAmt)}</span>
                                </div>
                            </div>

                            <div className="pt-3 border-top border-secondary">
                                <div className="d-flex justify-content-between align-items-baseline mb-2">
                                    <span style={{ fontSize: '13px', fontWeight: 'bold', color: '#94a3b8' }}>Total Amount</span>
                                    <span style={{ fontSize: '20px', fontWeight: 'bold', color: '#a855f7' }}>{fmtAED(totalAmount)}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* 2. Payments Made */}
                    <div className="col-lg-4">
                        <div className="p-4 rounded-4" style={{ background: 'rgba(30, 41, 59, 0.5)', border: '1px solid rgba(168, 85, 247, 0.15)', backdropFilter: 'blur(10px)', height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', boxShadow: '0 4px 20px rgba(0, 0, 0, 0.2)' }}>
                            <div>
                                <h5 className="fw-bold mb-3 d-flex align-items-center gap-2" style={{ fontSize: '13px', textTransform: 'uppercase', letterSpacing: '0.5px', color: '#22c55e' }}>
                                    <CreditCard size={16} /> Payments Made
                                </h5>
                                <div className="d-flex justify-content-between mb-2" style={{ fontSize: '12.5px', color: '#cbd5e1' }}>
                                    <span>Advance Paid</span>
                                    <span>{fmtAED(advancePaid)}</span>
                                </div>
                                <div className="d-flex justify-content-between mb-3" style={{ fontSize: '12.5px', color: '#cbd5e1' }}>
                                    <span>Other Payments</span>
                                    <span>{fmtAED(totalPaid - advancePaid)}</span>
                                </div>
                                <div className="d-flex justify-content-between pt-2 border-top border-secondary mb-4">
                                    <span style={{ fontSize: '12px', fontWeight: 'bold', color: '#94a3b8' }}>TOTAL PAID</span>
                                    <span style={{ fontSize: '16px', fontWeight: 'bold', color: '#22c55e' }}>{fmtAED(totalPaid)}</span>
                                </div>

                                <h5 className="fw-bold mb-3" style={{ fontSize: '13px', textTransform: 'uppercase', letterSpacing: '0.5px', color: '#eab308' }}>Security Deposit (Refundable)</h5>
                                <div className="d-flex justify-content-between mb-3" style={{ fontSize: '12.5px', color: '#cbd5e1' }}>
                                    <span>Security Deposit Collected</span>
                                    <span style={{ color: '#eab308', fontWeight: 'bold' }}>{fmtAED(securityDeposit)}</span>
                                </div>
                            </div>

                        </div>
                    </div>

                    {/* 3. Amount Due */}
                    <div className="col-lg-4">
                        <div className="p-4 rounded-4" style={{ background: 'rgba(30, 41, 59, 0.5)', border: '1px solid rgba(168, 85, 247, 0.15)', backdropFilter: 'blur(10px)', height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', boxShadow: '0 4px 20px rgba(0, 0, 0, 0.2)' }}>
                            <div>
                                <h5 className="fw-bold mb-3 d-flex align-items-center gap-2" style={{ fontSize: '13px', textTransform: 'uppercase', letterSpacing: '0.5px', color: '#ef4444' }}>
                                    <Wallet size={16} /> Amount Due
                                </h5>
                                
                                <div className="d-flex justify-content-between mb-2" style={{ fontSize: '12.5px', color: '#cbd5e1' }}>
                                    <span>Total Amount</span>
                                    <span>{fmtAED(totalAmount)}</span>
                                </div>
                                <div className="d-flex justify-content-between mb-3" style={{ fontSize: '12.5px', color: '#cbd5e1' }}>
                                    <span>(-) Total Paid</span>
                                    <span>{fmtAED(totalPaid)}</span>
                                </div>
                            </div>

                            <div className="pt-3 border-top border-secondary">
                                <div className="d-flex justify-content-between align-items-baseline mb-3">
                                    <span style={{ fontSize: '13px', fontWeight: 'bold', color: '#94a3b8' }}>BALANCE TO PAY</span>
                                    <span style={{ fontSize: '20px', fontWeight: 'bold', color: '#ef4444' }}>{fmtAED(remainingAmountDue)}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Payment History Table */}
            <div className="p-4 mb-4 rounded-4" style={{ background: 'rgba(30, 41, 59, 0.5)', border: '1px solid rgba(168, 85, 247, 0.15)', backdropFilter: 'blur(10px)', boxShadow: '0 4px 20px rgba(0, 0, 0, 0.2)' }}>
                <h5 className="fw-bold mb-4 d-flex align-items-center gap-2" style={{ fontSize: '14px', textTransform: 'uppercase', letterSpacing: '0.5px', color: '#a855f7' }}>
                    <Calendar size={18} /> Payment History
                </h5>
                <div className="table-responsive">
                    <table className="table table-borderless align-middle mb-0" style={{ '--bs-table-bg': 'transparent', '--bs-table-color': '#cbd5e1', fontSize: '12.5px' }}>
                        <thead>
                            <tr style={{ borderBottom: '1px solid rgba(168, 85, 247, 0.2)' }}>
                                <th style={{ color: '#94a3b8', fontWeight: '600', padding: '12px 16px', letterSpacing: '0.5px' }}>DATE & TIME</th>
                                <th style={{ color: '#94a3b8', fontWeight: '600', padding: '12px 16px', letterSpacing: '0.5px' }}>TYPE</th>
                                <th style={{ color: '#94a3b8', fontWeight: '600', padding: '12px 16px', letterSpacing: '0.5px' }}>DESCRIPTION</th>
                                <th style={{ color: '#94a3b8', fontWeight: '600', padding: '12px 16px', letterSpacing: '0.5px' }}>AMOUNT</th>
                                <th style={{ color: '#94a3b8', fontWeight: '600', padding: '12px 16px', letterSpacing: '0.5px' }}>PAYMENT MODE</th>
                                <th style={{ color: '#94a3b8', fontWeight: '600', padding: '12px 16px', letterSpacing: '0.5px' }}>RECEIPT</th>
                            </tr>
                        </thead>
                        <tbody>
                            {displayPaymentHistory.map((item, idx) => (
                                <tr key={idx} style={{ borderBottom: '1px solid rgba(255, 255, 255, 0.05)', transition: 'background 0.2s' }} onMouseOver={(e) => e.currentTarget.style.background = 'rgba(168, 85, 247, 0.05)'} onMouseOut={(e) => e.currentTarget.style.background = 'transparent'}>
                                    <td style={{ padding: '16px' }}>{formatDateStr(item.date)}</td>
                                    <td style={{ padding: '16px' }}>
                                        <span style={{ 
                                            background: item.type === 'Advance' ? 'rgba(59,130,246,0.12)' : item.type === 'Final' ? 'rgba(34,197,94,0.12)' : item.type === 'Deposit' ? 'rgba(168,85,247,0.12)' : 'rgba(234,179,8,0.12)', 
                                            color: item.type === 'Advance' ? '#3b82f6' : item.type === 'Final' ? '#22c55e' : item.type === 'Deposit' ? '#a855f7' : '#eab308', 
                                            padding: '4px 10px', 
                                            borderRadius: '6px', 
                                            fontWeight: '600' 
                                        }}>
                                            {item.type}
                                        </span>
                                    </td>
                                    <td style={{ padding: '16px', color: '#f8fafc' }}>{item.description}</td>
                                    <td style={{ padding: '16px', color: '#22c55e', fontWeight: 'bold' }}>{fmtAED(item.amount)}</td>
                                    <td style={{ padding: '16px' }}>{item.mode}</td>
                                    <td style={{ padding: '16px' }}>
                                        <button onClick={() => navigate(`/print/receipt/${booking.booking_id || booking.id}?index=${idx}`)} className="btn btn-link p-0" style={{ color: '#0ea5e9', transition: 'transform 0.2s' }} onMouseOver={(e) => e.currentTarget.style.transform = 'scale(1.1)'} onMouseOut={(e) => e.currentTarget.style.transform = 'scale(1)'}>
                                            <Printer size={16} />
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Collect payment action panel */}
            {!isPaid && booking.status !== 'cancelled' && (
                <div className="row g-3 align-items-center mb-4">
                    <div className="col-lg-4">
                        <div className="p-3 rounded-4" style={{ background: 'linear-gradient(135deg, rgba(239, 68, 68, 0.1), rgba(239, 68, 68, 0.05))', border: '1px solid rgba(239,68,68,0.2)', textAlign: 'center', boxShadow: '0 4px 20px rgba(239, 68, 68, 0.1)' }}>
                            <div style={{ fontSize: '11px', color: '#fca5a5', textTransform: 'uppercase', fontWeight: '600', letterSpacing: '0.5px' }}>Total to Collect Now</div>
                            <div style={{ fontSize: '24px', color: '#ef4444', fontWeight: 'bold', marginTop: '4px' }}>{fmtAED(remainingAmountDue)}</div>
                        </div>
                    </div>
                    <div className="col-lg-8">
                        <div className="d-flex gap-3 align-items-center p-3 rounded-4" style={{ background: 'rgba(30, 41, 59, 0.5)', border: '1px solid rgba(168, 85, 247, 0.15)', backdropFilter: 'blur(10px)' }}>
                            <div style={{
                                display: 'flex',
                                alignItems: 'center',
                                background: 'rgba(15, 23, 42, 0.6)',
                                border: '1px solid rgba(255, 255, 255, 0.1)',
                                borderRadius: '10px',
                                overflow: 'hidden',
                                flex: 1,
                                height: '42px',
                                transition: 'border-color 0.3s',
                            }}>
                                <span style={{
                                    background: 'rgba(255,255,255,0.03)',
                                    borderRight: '1px solid rgba(255, 255, 255, 0.05)',
                                    color: '#a855f7',
                                    padding: '0 16px',
                                    fontSize: '12px',
                                    fontWeight: 'bold',
                                    userSelect: 'none',
                                    height: '100%',
                                    display: 'flex',
                                    alignItems: 'center'
                                }}>
                                    AED
                                </span>
                                <input 
                                    type="number" 
                                    className="bg-transparent border-0 text-white px-3" 
                                    placeholder="Enter amount received"
                                    value={collectAmt}
                                    onChange={(e) => setCollectAmt(e.target.value)}
                                    style={{ 
                                        fontSize: '14px', 
                                        outline: 'none', 
                                        width: '100%',
                                        color: '#ffffff',
                                        fontWeight: '500'
                                    }}
                                />
                            </div>
                            <button 
                                onClick={handleCollectPayment}
                                className="btn text-white fw-bold d-flex align-items-center gap-2 px-4"
                                style={{ background: 'linear-gradient(135deg, #a855f7 0%, #7c3aed 100%)', border: 'none', borderRadius: '10px', whiteSpace: 'nowrap', height: '42px', fontSize: '13px', boxShadow: '0 4px 15px rgba(168, 85, 247, 0.3)' }}
                            >
                                <CheckCircle size={16} /> Collect Payment
                            </button>
                            <span style={{ fontSize: '12px', color: '#64748b', fontWeight: '600' }}>OR</span>
                            <button 
                                onClick={handleMarkAsPaid}
                                className="btn fw-bold d-flex align-items-center gap-2 px-4"
                                style={{ background: 'rgba(168, 85, 247, 0.1)', border: '1px solid rgba(168, 85, 247, 0.4)', borderRadius: '10px', color: '#a855f7', whiteSpace: 'nowrap', height: '42px', fontSize: '13px', transition: 'all 0.2s' }}
                                onMouseOver={(e) => { e.currentTarget.style.background = 'rgba(168, 85, 247, 0.2)'; e.currentTarget.style.color = '#fff'; }}
                                onMouseOut={(e) => { e.currentTarget.style.background = 'rgba(168, 85, 247, 0.1)'; e.currentTarget.style.color = '#a855f7'; }}
                            >
                                Mark as Fully Paid
                            </button>
                        </div>
                    </div>
                </div>
            )}
            
            {/* Important Information list at bottom */}
            <div className="p-4 rounded-4" style={{ background: 'rgba(30, 41, 59, 0.5)', border: '1px solid rgba(168, 85, 247, 0.15)', backdropFilter: 'blur(10px)', boxShadow: '0 4px 20px rgba(0, 0, 0, 0.2)' }}>
                <h5 className="fw-bold mb-3 d-flex align-items-center gap-2" style={{ fontSize: '13px', textTransform: 'uppercase', letterSpacing: '0.5px', color: '#a855f7' }}>
                    <Info size={16} /> Important Information
                </h5>
                <ol style={{ fontSize: '12.5px', color: '#cbd5e1', paddingLeft: '18px', margin: 0, lineHeight: '1.8' }}>
                    {booking.status === 'cancelled' ? (
                        <>
                            <li>The trip was cancelled before starting; rental charges are not applicable.</li>
                            <li>The Security Deposit ({fmtAED(securityDeposit)}) is refundable and must be returned to the customer separately.</li>
                            <li>The Advance Payment ({fmtAED(advancePaid)}) has been logged and should be settled/refunded as per cancellation policies.</li>
                        </>
                    ) : (
                        <>
                            <li>Total Amount is the final rental charge (Base Price + Tax - Discount)</li>
                            <li>This is a refundable amount. It will be returned to the customer separately.</li>
                            <li>
                                {remainingAmountDue > 0 ? (
                                    <>Customer has not paid the full amount. Please collect <span className="text-danger fw-bold">{fmtAED(remainingAmountDue)}</span>.</>
                                ) : (
                                    <>Customer has paid the full amount. Booking is fully settled.</>
                                )}
                            </li>
                        </>
                    )}
                </ol>
            </div>
        </div>
    );
};

export default FinalSummary;
