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

export default function Print({ payment, settings }) {
    const owner = payment.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 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, #166534, #22c55e, #166534)', borderRadius: '2px', marginBottom: '10px' }} />

            {/* Header Row */}
            <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: '#166534', 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: Voucher meta */}
                <div style={{ textAlign: 'right' }}>
                    <span style={{
                        display: 'inline-block',
                        fontSize: '9px',
                        fontWeight: 700,
                        letterSpacing: '1.5px',
                        color: copyType === 'owner' ? '#166534' : '#6b21a8',
                        background: copyType === 'owner' ? '#dcfce7' : '#f3e8ff',
                        padding: '2px 10px',
                        borderRadius: '3px',
                        marginBottom: '4px',
                    }}>
                        {copyType === 'owner' ? 'OWNER COPY' : 'OFFICE COPY'}
                    </span>
                    <p style={{ margin: 0, fontSize: '10px', color: '#888' }}>Voucher No</p>
                    <p style={{ margin: 0, fontSize: '12px', fontWeight: 700, color: '#111' }}>{payment.voucher_number}</p>
                    <p style={{ margin: 0, fontSize: '10px', color: '#888', marginTop: '2px' }}>Date: {formatDate(payment.payment_date)}</p>
                </div>
            </div>

            {/* Title */}
            <div style={{ textAlign: 'center', margin: '0 0 10px' }}>
                <h2 style={{
                    display: 'inline-block',
                    margin: 0,
                    fontSize: '13px',
                    fontWeight: 700,
                    letterSpacing: '2px',
                    color: '#14532d',
                    borderBottom: '2px solid #166534',
                    paddingBottom: '2px',
                }}>
                    OWNER PAYMENT VOUCHER
                </h2>
            </div>

            {/* Owner Info Cards */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '10px' }}>
                <div style={{ background: '#f0fdf4', border: '1px solid #bbf7d0', borderRadius: '8px', padding: '8px 10px' }}>
                    <p style={{ margin: 0, fontSize: '9px', fontWeight: 600, color: '#888', textTransform: 'uppercase', letterSpacing: '0.5px' }}>Paid To (Owner)</p>
                    <p style={{ margin: '2px 0 0', fontSize: '12px', fontWeight: 700, color: '#111' }}>{owner?.name || '—'}</p>
                    <p style={{ margin: '1px 0 0', fontSize: '10px', color: '#666' }}>CNIC: {owner?.cnic || '—'}</p>
                    <p style={{ margin: '1px 0 0', fontSize: '10px', color: '#666' }}>Phone: {owner?.phone || '—'}</p>
                </div>
                <div style={{ background: '#f0fdf4', border: '1px solid #bbf7d0', borderRadius: '8px', padding: '8px 10px' }}>
                    <p style={{ margin: 0, fontSize: '9px', fontWeight: 600, color: '#888', textTransform: 'uppercase', letterSpacing: '0.5px' }}>Payment Details</p>
                    <p style={{ margin: '2px 0 0', fontSize: '12px', fontWeight: 700, color: '#111', textTransform: 'capitalize' }}>{payment.payment_method?.replace('_', ' ')}</p>
                    {owner?.bank_name && (
                        <p style={{ margin: '1px 0 0', fontSize: '10px', color: '#666' }}>Bank: {owner.bank_name}</p>
                    )}
                    {owner?.bank_account_no && (
                        <p style={{ margin: '1px 0 0', fontSize: '10px', color: '#666' }}>A/C: {owner.bank_account_no}</p>
                    )}
                </div>
            </div>

            {/* Items Table */}
            <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: '8px', fontSize: '11px' }}>
                <thead>
                    <tr style={{ background: '#166534' }}>
                        <th style={{ color: '#fff', padding: '5px 8px', textAlign: 'center', fontWeight: 600, fontSize: '10px', width: '30px' }}>#</th>
                        <th style={{ color: '#fff', padding: '5px 8px', textAlign: 'left', fontWeight: 600, fontSize: '10px' }}>Shop No.</th>
                        <th style={{ color: '#fff', padding: '5px 8px', textAlign: 'left', fontWeight: 600, fontSize: '10px' }}>Month</th>
                        <th style={{ color: '#fff', padding: '5px 8px', textAlign: 'right', fontWeight: 600, fontSize: '10px' }}>Amount (PKR)</th>
                    </tr>
                </thead>
                <tbody>
                    {payment.items?.map((item, idx) => (
                        <tr key={item.id} style={{ borderBottom: '1px solid #e5e7eb', background: idx % 2 === 0 ? '#fff' : '#f9fafb' }}>
                            <td style={{ padding: '4px 8px', textAlign: 'center', color: '#888' }}>{idx + 1}</td>
                            <td style={{ padding: '4px 8px', fontWeight: 600 }}>Shop {item.shop?.shop_number || '—'}</td>
                            <td style={{ padding: '4px 8px', color: '#555' }}>{formatMonth(item.month)}</td>
                            <td style={{ padding: '4px 8px', textAlign: 'right', fontWeight: 600 }}>{formatCurrency(item.amount)}</td>
                        </tr>
                    ))}
                </tbody>
            </table>

            {/* Amount Box */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: '#f0fdf4', border: '2px solid #166534', borderRadius: '8px', padding: '8px 12px', marginBottom: '6px' }}>
                <div>
                    <p style={{ margin: 0, fontSize: '9px', fontWeight: 600, color: '#888', textTransform: 'uppercase' }}>Amount in Words</p>
                    <p style={{ margin: '2px 0 0', fontSize: '11px', fontWeight: 600, color: '#111', fontStyle: 'italic' }}>{amountInWords(payment.total_amount)}</p>
                </div>
                <div style={{ textAlign: 'right' }}>
                    <p style={{ margin: 0, fontSize: '9px', fontWeight: 600, color: '#888', textTransform: 'uppercase' }}>Total Amount</p>
                    <p style={{ margin: 0, fontSize: '18px', fontWeight: 800, color: '#166534' }}>{formatCurrency(payment.total_amount)}</p>
                </div>
            </div>

            {/* PAID Badge */}
            <div style={{ textAlign: 'center', marginBottom: '8px' }}>
                <span style={{
                    display: 'inline-block',
                    background: '#166534',
                    color: '#fff',
                    fontSize: '11px',
                    fontWeight: 800,
                    letterSpacing: '3px',
                    padding: '3px 20px',
                    borderRadius: '4px',
                }}>
                    ✓ PAID
                </span>
                {payment.owner_signature_taken && (
                    <span style={{
                        display: 'inline-block',
                        background: '#f59e0b',
                        color: '#fff',
                        fontSize: '9px',
                        fontWeight: 700,
                        letterSpacing: '1px',
                        padding: '3px 10px',
                        borderRadius: '4px',
                        marginLeft: '6px',
                    }}>
                        SIGNATURE COLLECTED ✓
                    </span>
                )}
            </div>

            {/* Signatures */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginTop: '16px' }}>
                <div style={{ textAlign: 'center' }}>
                    <div style={{ width: '150px', borderBottom: '1.5px solid #333', marginBottom: '3px' }} />
                    <p style={{ margin: 0, fontSize: '10px', fontWeight: 600, color: '#555' }}>Manager Signature</p>
                </div>
                <div style={{ textAlign: 'center' }}>
                    <div style={{ width: '150px', borderBottom: '1.5px solid #333', marginBottom: '3px' }} />
                    <p style={{ margin: 0, fontSize: '10px', fontWeight: 600, color: '#555' }}>Owner Signature</p>
                </div>
            </div>

            {/* Bottom Accent Bar */}
            <div style={{ height: '3px', background: 'linear-gradient(90deg, #166534, #22c55e, #166534)', borderRadius: '2px', marginTop: '10px' }} />
        </div>
    );

    return (
        <>
            <Head title={`Voucher - ${payment.voucher_number}`} />

            <style>{`
                @media print {
                    .no-print { display: none !important; }
                    body { margin: 0; padding: 0; }
                    @page { size: A4 portrait; margin: 0; }
                }
                @media screen {
                    .print-page { max-width: 210mm; margin: 20px auto; box-shadow: 0 4px 24px rgba(0,0,0,.12); border-radius: 8px; }
                }
            `}</style>

            {/* Action Buttons */}
            <div className="no-print" style={{ maxWidth: '210mm', margin: '20px auto', display: 'flex', gap: '10px', padding: '0 10px' }}>
                <button
                    onClick={() => window.print()}
                    className="inline-flex items-center gap-2 rounded-lg bg-green-600 px-5 py-2.5 text-sm font-medium text-white hover:bg-green-700 shadow-sm"
                >
                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor"><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 Voucher
                </button>
                <button
                    onClick={() => window.history.back()}
                    className="inline-flex items-center gap-2 rounded-lg bg-gray-200 px-5 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-300"
                >
                    Back
                </button>
            </div>

            {/* A4 Page - Two Copies */}
            <div className="print-page" style={{ width: '210mm', minHeight: '297mm', background: '#fff', overflow: 'hidden' }}>
                {renderCopy('owner')}
                {/* Dashed Cut Line */}
                <div style={{ borderTop: '2px dashed #aaa', margin: '0 5mm', position: 'relative' }}>
                    <span style={{ position: 'absolute', top: '-8px', left: '50%', transform: 'translateX(-50%)', background: '#fff', padding: '0 8px', fontSize: '9px', color: '#aaa' }}>✂ CUT HERE</span>
                </div>
                {renderCopy('office')}
            </div>
        </>
    );
}
