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

export default function Show({ invoice }) {
    const lease = invoice.lease;
    const tenant = lease?.tenant;
    const shop = lease?.shop;
    const owner = shop?.owner;
    const payments = invoice.payments || [];
    const totalPaid = payments.reduce((sum, p) => sum + parseFloat(p.amount_paid || 0), 0);
    const balance = parseFloat(invoice.total_amount) - totalPaid;
    const paidPercent = parseFloat(invoice.total_amount) > 0 ? Math.min((totalPaid / parseFloat(invoice.total_amount)) * 100, 100) : 0;

    const statusBadge = (status) => {
        const styles = {
            paid: 'bg-green-100 text-green-800',
            partial: 'bg-yellow-100 text-yellow-800',
            overdue: 'bg-red-100 text-red-800',
            pending: 'bg-gray-100 text-gray-800',
        };
        return (
            <span className={`inline-flex items-center rounded-full px-3 py-1 text-sm font-medium ${styles[status] || styles.pending}`}>
                {status.charAt(0).toUpperCase() + status.slice(1)}
            </span>
        );
    };

    return (
        <AuthenticatedLayout header={<h2 className="text-xl font-semibold leading-tight text-gray-800">Invoice Details</h2>}>
            <Head title={`Invoice ${invoice.invoice_number}`} />

            <div className="py-12">
                <div className="mx-auto max-w-7xl sm:px-6 lg:px-8 space-y-6">
                    {/* Invoice Info Card */}
                    <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <div className="flex items-center justify-between mb-6">
                                <div>
                                    <h3 className="text-lg font-medium">{invoice.invoice_number}</h3>
                                    <p className="text-sm text-gray-500">{formatMonth(invoice.month)}</p>
                                </div>
                                <div className="flex items-center gap-2">
                                    <Link
                                        href={route('payments.create', { invoice_id: invoice.id })}
                                        className="inline-flex items-center rounded-md bg-green-600 px-4 py-2 text-sm font-medium text-white hover:bg-green-700"
                                    >
                                        Record Payment
                                    </Link>
                                    <Link
                                        href={route('invoices.print', invoice.id)}
                                        className="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700"
                                    >
                                        Print Invoice
                                    </Link>
                                    <Link href={route('invoices.index')} className="inline-flex items-center rounded-md bg-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-300">Back</Link>
                                </div>
                            </div>

                            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                {/* Tenant & Shop Info */}
                                <div>
                                    <h4 className="text-sm font-semibold text-gray-700 mb-3">Tenant & Shop</h4>
                                    <dl className="space-y-2">
                                        <div className="flex justify-between">
                                            <dt className="text-sm text-gray-500">Tenant</dt>
                                            <dd className="text-sm font-medium text-gray-900">{tenant?.name || '—'}</dd>
                                        </div>
                                        <div className="flex justify-between">
                                            <dt className="text-sm text-gray-500">Phone</dt>
                                            <dd className="text-sm text-gray-900">{tenant?.phone || '—'}</dd>
                                        </div>
                                        <div className="flex justify-between">
                                            <dt className="text-sm text-gray-500">CNIC</dt>
                                            <dd className="text-sm text-gray-900">{tenant?.cnic || '—'}</dd>
                                        </div>
                                        <div className="flex justify-between">
                                            <dt className="text-sm text-gray-500">Shop #</dt>
                                            <dd className="text-sm text-gray-900">{shop?.shop_number || '—'}</dd>
                                        </div>
                                        <div className="flex justify-between">
                                            <dt className="text-sm text-gray-500">Owner</dt>
                                            <dd className="text-sm text-gray-900">{owner?.name || '—'}</dd>
                                        </div>
                                    </dl>
                                </div>

                                {/* Charges Breakdown */}
                                <div>
                                    <h4 className="text-sm font-semibold text-gray-700 mb-3">Charges Breakdown</h4>
                                    <dl className="space-y-2">
                                        <div className="flex justify-between">
                                            <dt className="text-sm text-gray-500">Rent</dt>
                                            <dd className="text-sm text-gray-900">{formatCurrency(invoice.rent_amount)}</dd>
                                        </div>
                                        <div className="flex justify-between">
                                            <dt className="text-sm text-gray-500">Electricity</dt>
                                            <dd className="text-sm text-gray-900">{formatCurrency(invoice.electricity_amount)}</dd>
                                        </div>
                                        <div className="flex justify-between">
                                            <dt className="text-sm text-gray-500">Maintenance</dt>
                                            <dd className="text-sm text-gray-900">{formatCurrency(invoice.maintenance_amount)}</dd>
                                        </div>
                                        {parseFloat(invoice.other_charges) > 0 && (
                                            <div className="flex justify-between">
                                                <dt className="text-sm text-gray-500">Other ({invoice.other_charges_description || 'Charges'})</dt>
                                                <dd className="text-sm text-gray-900">{formatCurrency(invoice.other_charges)}</dd>
                                            </div>
                                        )}
                                        <div className="flex justify-between border-t pt-2">
                                            <dt className="text-sm font-semibold text-gray-700">Total</dt>
                                            <dd className="text-sm font-semibold text-gray-900">{formatCurrency(invoice.total_amount)}</dd>
                                        </div>
                                    </dl>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Payment Status */}
                    <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <div className="flex items-center justify-between mb-4">
                                <h4 className="text-sm font-semibold text-gray-700">Payment Status</h4>
                                {statusBadge(invoice.status)}
                            </div>
                            <div className="flex items-center justify-between text-sm text-gray-500 mb-2">
                                <span>Paid: {formatCurrency(totalPaid)}</span>
                                <span>Total: {formatCurrency(invoice.total_amount)}</span>
                            </div>
                            <div className="w-full bg-gray-200 rounded-full h-3">
                                <div
                                    className={`h-3 rounded-full ${paidPercent >= 100 ? 'bg-green-500' : paidPercent > 0 ? 'bg-yellow-500' : 'bg-gray-300'}`}
                                    style={{ width: `${paidPercent}%` }}
                                ></div>
                            </div>
                            <p className="mt-1 text-sm text-gray-500">Balance: {formatCurrency(balance)}</p>
                        </div>
                    </div>

                    {/* Payments Table */}
                    <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <h4 className="text-sm font-semibold text-gray-700 mb-4">Payments ({payments.length})</h4>
                            {payments.length > 0 ? (
                                <div className="overflow-x-auto">
                                    <table className="min-w-full divide-y divide-gray-200">
                                        <thead className="bg-gray-50">
                                            <tr>
                                                <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Date</th>
                                                <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">Amount</th>
                                                <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Method</th>
                                                <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Proof</th>
                                                <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Received By</th>
                                                <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Remarks</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-gray-200 bg-white">
                                            {payments.map((payment) => (
                                                <tr key={payment.id} className="hover:bg-gray-50">
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-500">{formatDate(payment.payment_date)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right font-medium text-gray-900">{formatCurrency(payment.amount_paid)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-500 capitalize">{payment.payment_method?.replace('_', ' ')}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-500">
                                                        {payment.proof_file ? (
                                                            <a href={`/storage/${payment.proof_file}`} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:text-blue-900">View</a>
                                                        ) : '—'}
                                                    </td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-500">{payment.received_by || '—'}</td>
                                                    <td className="px-4 py-4 text-sm text-gray-500">{payment.remarks || '—'}</td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            ) : (
                                <p className="text-sm text-gray-500">No payments recorded yet.</p>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
