import { Head } from '@inertiajs/react';
import { formatCurrency, formatDate } from '@/utils';

export default function CommissionReceipt({ lease, settings }) {
    const tenant = lease.tenant;
    const shop = lease.shop;
    const owner = shop?.owner;

    const businessName = settings?.business_name || 'RentDesk';
    const businessAddress = settings?.business_address || '';
    const businessPhone = settings?.business_phone || '';
    const businessLogo = settings?.business_logo ? `/storage/${settings.business_logo}` : null;

    const commissionLabel =
        lease.commission_type === 'full_rent' ? 'Full Month Rent'
        : lease.commission_type === 'half_rent' ? 'Half Month Rent'
        : 'Fixed Amount';

    const receiptNo = `COM-${lease.id}-${new Date(lease.commission_paid_date || Date.now()).getFullYear()}`;
    const paidDate = lease.commission_paid_date ? formatDate(lease.commission_paid_date) : formatDate(new Date());

    const amountInWords = (num) => {
        const ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
            'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
        const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
        const n = Math.floor(Math.abs(num));
        if (n === 0) return 'Zero Rupees Only';
        const lakh = Math.floor(n / 100000);
        const thousand = Math.floor((n % 100000) / 1000);
        const hundred = Math.floor((n % 1000) / 100);
        const rem = n % 100;
        const twoDigit = (v) => v < 20 ? ones[v] : tens[Math.floor(v / 10)] + (v % 10 ? ' ' + ones[v % 10] : '');
        let str = '';
        if (lakh) str += twoDigit(lakh) + ' Lakh ';
        if (thousand) str += twoDigit(thousand) + ' Thousand ';
        if (hundred) str += ones[hundred] + ' Hundred ';
        if (rem) str += (str ? 'and ' : '') + twoDigit(rem);
        return str.trim() + ' Rupees Only';
    };

    const renderCopy = (copyType) => (
        <div style={{ height: '48%', padding: '6mm 5mm', boxSizing: 'border-box', position: 'relative', fontFamily: "'Segoe UI', Arial, sans-serif" }}>

            {/* Top Accent Bar */}
            <div style={{ height: '4px', background: 'linear-gradient(90deg, #1e40af, #3b82f6, #1e40af)', borderRadius: '2px', marginBottom: '10px' }} />

            {/* Header Row: Business + Copy Badge + Receipt Info */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>
                {/* Left: Business */}
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                    {businessLogo ? (
                        <img src={businessLogo} alt={businessName} style={{ height: '38px', objectFit: 'contain' }} />
                    ) : (
                        <div style={{ width: '38px', height: '38px', borderRadius: '8px', background: '#1e40af', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: '16px' }}>
                            {businessName.charAt(0)}
                        </div>
                    )}
                    <div>
                        <h1 style={{ margin: 0, fontSize: '16px', fontWeight: 700, color: '#111' }}>{businessName}</h1>
                        {businessAddress && <p style={{ margin: 0, fontSize: '10px', color: '#666' }}>{businessAddress}</p>}
                        {businessPhone && <p style={{ margin: 0, fontSize: '10px', color: '#666' }}>Tel: {businessPhone}</p>}
                    </div>
                </div>

                {/* Right: Receipt meta */}
                <div style={{ textAlign: 'right' }}>
                    <span style={{
                        display: 'inline-block',
                        fontSize: '9px',
                        fontWeight: 700,
                        letterSpacing: '1.5px',
                        color: copyType === 'customer' ? '#1e40af' : '#6b21a8',
                        background: copyType === 'customer' ? '#dbeafe' : '#f3e8ff',
                        padding: '2px 10px',
                        borderRadius: '3px',
                        marginBottom: '4px',
                    }}>
                        {copyType === 'customer' ? 'CUSTOMER COPY' : 'OFFICE COPY'}
                    </span>
                    <p style={{ margin: 0, fontSize: '10px', color: '#888' }}>Receipt No</p>
                    <p style={{ margin: 0, fontSize: '12px', fontWeight: 700, color: '#111' }}>{receiptNo}</p>
                    <p style={{ margin: 0, fontSize: '10px', color: '#888', marginTop: '2px' }}>Date: {paidDate}</p>
                </div>
            </div>

            {/* Title */}
            <div style={{ textAlign: 'center', margin: '0 0 12px' }}>
                <h2 style={{
                    display: 'inline-block',
                    margin: 0,
                    fontSize: '13px',
                    fontWeight: 700,
                    letterSpacing: '2px',
                    color: '#1e3a5f',
                    borderBottom: '2px solid #1e40af',
                    paddingBottom: '2px',
                }}>
                    REFERRAL COMMISSION PAYMENT RECEIPT
                </h2>
            </div>

            {/* Two Column Info Cards */}
            <div style={{ display: 'flex', gap: '10px', marginBottom: '10px' }}>
                {/* Left: Paid To */}
                <div style={{ flex: 1, border: '1px solid #e5e7eb', borderRadius: '6px', padding: '8px 10px', background: '#f8fafc' }}>
                    <p style={{ margin: 0, fontSize: '9px', fontWeight: 600, color: '#888', textTransform: 'uppercase', letterSpacing: '0.5px' }}>Commission Paid To</p>
                    <p style={{ margin: '2px 0 0', fontSize: '13px', fontWeight: 700, color: '#111' }}>{lease.commission_to || '—'}</p>
                    <p style={{ margin: '1px 0 0', fontSize: '10px', color: '#666' }}>{lease.commission_phone || 'No phone'}</p>
                </div>
                {/* Right: Property */}
                <div style={{ flex: 1, border: '1px solid #e5e7eb', borderRadius: '6px', padding: '8px 10px', background: '#f8fafc' }}>
                    <p style={{ margin: 0, fontSize: '9px', fontWeight: 600, color: '#888', textTransform: 'uppercase', letterSpacing: '0.5px' }}>Property Details</p>
                    <p style={{ margin: '2px 0 0', fontSize: '13px', fontWeight: 700, color: '#111' }}>Shop #{shop?.shop_number || '—'}</p>
                    <p style={{ margin: '1px 0 0', fontSize: '10px', color: '#666' }}>
                        {[shop?.location, shop?.floor ? `Floor: ${shop.floor}` : null].filter(Boolean).join(' | ') || 'No location'}
                    </p>
                </div>
            </div>

            {/* Details Grid */}
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '11px', marginBottom: '8px' }}>
                <thead>
                    <tr style={{ background: '#1e40af' }}>
                        <th style={{ padding: '5px 10px', color: '#fff', fontWeight: 600, textAlign: 'left', fontSize: '10px', letterSpacing: '0.5px' }}>DESCRIPTION</th>
                        <th style={{ padding: '5px 10px', color: '#fff', fontWeight: 600, textAlign: 'right', fontSize: '10px', letterSpacing: '0.5px', width: '140px' }}>DETAILS</th>
                    </tr>
                </thead>
                <tbody>
                    <tr style={{ borderBottom: '1px solid #e5e7eb' }}>
                        <td style={{ padding: '5px 10px', color: '#555' }}>Tenant Name</td>
                        <td style={{ padding: '5px 10px', textAlign: 'right', fontWeight: 500, color: '#111' }}>{tenant?.name || '—'}</td>
                    </tr>
                    <tr style={{ borderBottom: '1px solid #e5e7eb', background: '#fafbfc' }}>
                        <td style={{ padding: '5px 10px', color: '#555' }}>Property Owner</td>
                        <td style={{ padding: '5px 10px', textAlign: 'right', fontWeight: 500, color: '#111' }}>{owner?.name || '—'}</td>
                    </tr>
                    <tr style={{ borderBottom: '1px solid #e5e7eb' }}>
                        <td style={{ padding: '5px 10px', color: '#555' }}>Commission Type</td>
                        <td style={{ padding: '5px 10px', textAlign: 'right', fontWeight: 500, color: '#111' }}>{commissionLabel}</td>
                    </tr>
                    <tr style={{ borderBottom: '1px solid #e5e7eb', background: '#fafbfc' }}>
                        <td style={{ padding: '5px 10px', color: '#555' }}>Agreed Monthly Rent</td>
                        <td style={{ padding: '5px 10px', textAlign: 'right', fontWeight: 500, color: '#111' }}>{formatCurrency(lease.agreed_rent)}</td>
                    </tr>
                </tbody>
            </table>

            {/* Amount Box */}
            <div style={{
                border: '2px solid #1e40af',
                borderRadius: '8px',
                overflow: 'hidden',
                marginBottom: '8px',
            }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 14px', background: '#eff6ff' }}>
                    <div>
                        <p style={{ margin: 0, fontSize: '10px', fontWeight: 600, color: '#1e40af', textTransform: 'uppercase', letterSpacing: '0.5px' }}>Total Commission Paid</p>
                        <p style={{ margin: '1px 0 0', fontSize: '9px', color: '#6b7280', fontStyle: 'italic' }}>{amountInWords(lease.commission_amount)}</p>
                    </div>
                    <div style={{ fontSize: '20px', fontWeight: 800, color: '#1e40af' }}>
                        {formatCurrency(lease.commission_amount)}
                    </div>
                </div>
                <div style={{ height: '3px', background: 'linear-gradient(90deg, #1e40af, #3b82f6, #60a5fa)' }} />
            </div>

            {/* Remarks + Status Row */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px', fontSize: '10px' }}>
                <div style={{ color: '#666', flex: 1 }}>
                    {lease.commission_remarks && (
                        <span><span style={{ fontWeight: 600, color: '#555' }}>Note:</span> {lease.commission_remarks}</span>
                    )}
                </div>
                <span style={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: '4px',
                    background: '#dcfce7',
                    color: '#166534',
                    fontWeight: 700,
                    fontSize: '10px',
                    padding: '3px 12px',
                    borderRadius: '99px',
                    letterSpacing: '0.5px',
                    flexShrink: 0,
                }}>
                    ✓ PAID
                </span>
            </div>

            {/* Signatures */}
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '8px', paddingTop: '0' }}>
                <div style={{ textAlign: 'center', width: '180px' }}>
                    <div style={{ borderBottom: '1.5px solid #374151', marginBottom: '4px', height: '28px' }} />
                    <p style={{ margin: 0, fontSize: '10px', fontWeight: 600, color: '#374151' }}>Receiver's Signature</p>
                    <p style={{ margin: 0, fontSize: '9px', color: '#9ca3af' }}>{lease.commission_to || ''}</p>
                </div>
                <div style={{ textAlign: 'center', width: '180px' }}>
                    <div style={{ borderBottom: '1.5px solid #374151', marginBottom: '4px', height: '28px' }} />
                    <p style={{ margin: 0, fontSize: '10px', fontWeight: 600, color: '#374151' }}>Authorized Signature</p>
                    <p style={{ margin: 0, fontSize: '9px', color: '#9ca3af' }}>{businessName}</p>
                </div>
            </div>

            {/* Bottom Accent */}
            <div style={{ height: '3px', background: 'linear-gradient(90deg, #1e40af, #3b82f6, #1e40af)', borderRadius: '2px', marginTop: '8px' }} />
        </div>
    );

    return (
        <>
            <Head title={`Commission Receipt - ${receiptNo}`} />

            <style>{`
                @media print {
                    @page { size: A4; margin: 6mm; }
                    body { margin: 0; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                    .no-print { display: none !important; }
                }
                @media screen {
                    body { background: #e5e7eb; }
                }
            `}</style>

            {/* Action Buttons */}
            <div className="no-print" style={{ position: 'fixed', top: '16px', right: '16px', zIndex: 50, display: 'flex', gap: '8px' }}>
                <button
                    onClick={() => window.print()}
                    style={{
                        display: 'inline-flex', alignItems: 'center', gap: '6px',
                        padding: '10px 20px', borderRadius: '8px',
                        background: '#1e40af', color: '#fff', border: 'none',
                        fontSize: '14px', fontWeight: 600, cursor: 'pointer',
                        boxShadow: '0 4px 12px rgba(30,64,175,0.3)',
                    }}
                >
                    <svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2"><path strokeLinecap="round" strokeLinejoin="round" d="M6.72 13.829c-.24.03-.48.062-.72.096m.72-.096a42.415 42.415 0 0 1 10.56 0m-10.56 0L6.34 18m10.94-4.171c.24.03.48.062.72.096m-.72-.096L17.66 18m0 0 .229 2.523a1.125 1.125 0 0 1-1.12 1.227H7.231c-.662 0-1.18-.568-1.12-1.227L6.34 18m11.318 0h1.091A2.25 2.25 0 0 0 21 15.75V9.456c0-1.081-.768-2.015-1.837-2.175a48.055 48.055 0 0 0-1.913-.247M6.34 18H5.25A2.25 2.25 0 0 1 3 15.75V9.456c0-1.081.768-2.015 1.837-2.175a48.041 48.041 0 0 1 1.913-.247m10.5 0a48.536 48.536 0 0 0-10.5 0m10.5 0V3.375c0-.621-.504-1.125-1.125-1.125h-8.25c-.621 0-1.125.504-1.125 1.125v3.659M18.75 7.131a48.041 48.041 0 0 0-1.913-.247M6.75 7.131a48.041 48.041 0 0 1-1.913-.247" /></svg>
                    Print Receipt
                </button>
                <button
                    onClick={() => window.history.back()}
                    style={{
                        display: 'inline-flex', alignItems: 'center', gap: '6px',
                        padding: '10px 20px', borderRadius: '8px',
                        background: '#f3f4f6', color: '#374151', border: '1px solid #d1d5db',
                        fontSize: '14px', fontWeight: 500, cursor: 'pointer',
                    }}
                >
                    ← Back
                </button>
            </div>

            {/* A4 Page */}
            <div
                style={{
                    width: '210mm',
                    minHeight: '297mm',
                    margin: '0 auto',
                    background: '#fff',
                    fontFamily: "'Segoe UI', Arial, sans-serif",
                    color: '#111',
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'space-between',
                    boxShadow: '0 0 20px rgba(0,0,0,0.08)',
                }}
            >
                {/* Customer Copy */}
                {renderCopy('customer')}

                {/* Cut Line */}
                <div style={{ position: 'relative', margin: '0 5mm', height: '0' }}>
                    <div style={{ borderTop: '2px dashed #cbd5e1', width: '100%' }} />
                    <span style={{
                        position: 'absolute',
                        top: '-9px',
                        left: '50%',
                        transform: 'translateX(-50%)',
                        background: '#fff',
                        padding: '0 12px',
                        fontSize: '12px',
                        color: '#94a3b8',
                        letterSpacing: '2px',
                    }}>
                        ✂ · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · ·
                    </span>
                </div>

                {/* Office Copy */}
                {renderCopy('office')}
            </div>
        </>
    );
}
