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

export default function Collection({ invoices, month, totalExpected, totalCollected, pending }) {
    const [currentMonth, setCurrentMonth] = useState(month || new Date().toISOString().slice(0, 7));

    const handleMonthChange = (m) => {
        setCurrentMonth(m);
        router.get(route('reports.collection'), { month: m }, { preserveState: true, replace: true });
    };

    return (
        <AuthenticatedLayout header={<h2 className="text-xl font-semibold leading-tight text-gray-800">Monthly Collection</h2>}>
            <Head title="Monthly Collection" />

            <div className="py-12">
                <div className="mx-auto max-w-7xl sm:px-6 lg:px-8 space-y-6">
                    {/* Controls */}
                    <div className="bg-white shadow-sm sm:rounded-lg p-6">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-4">
                                <label className="text-sm font-medium text-gray-700">Month:</label>
                                <input
                                    type="month"
                                    value={currentMonth}
                                    onChange={(e) => handleMonthChange(e.target.value)}
                                    className="rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                />
                            </div>
                            <Link href={route('reports.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 to Reports</Link>
                        </div>
                    </div>

                    {/* Summary Cards */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div className="bg-white shadow-sm sm:rounded-lg p-6 border-l-4 border-blue-500">
                            <p className="text-sm font-medium text-gray-500">Expected</p>
                            <p className="text-2xl font-bold text-blue-700">{formatCurrency(totalExpected)}</p>
                        </div>
                        <div className="bg-white shadow-sm sm:rounded-lg p-6 border-l-4 border-green-500">
                            <p className="text-sm font-medium text-gray-500">Collected</p>
                            <p className="text-2xl font-bold text-green-700">{formatCurrency(totalCollected)}</p>
                        </div>
                        <div className="bg-white shadow-sm sm:rounded-lg p-6 border-l-4 border-yellow-500">
                            <p className="text-sm font-medium text-gray-500">Pending</p>
                            <p className="text-2xl font-bold text-yellow-700">{formatCurrency(pending)}</p>
                        </div>
                    </div>

                    {/* Table */}
                    <div className="bg-white shadow-sm sm:rounded-lg overflow-hidden">
                        <div className="p-6 text-gray-900">
                            <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">Invoice#</th>
                                            <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Shop#</th>
                                            <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Tenant</th>
                                            <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">Total</th>
                                            <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">Paid</th>
                                            <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">Balance</th>
                                            <th className="px-4 py-3 text-center text-xs font-medium uppercase tracking-wider text-gray-500">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-200 bg-white">
                                        {invoices.map((invoice) => {
                                            const paid = (invoice.payments || []).reduce((sum, p) => sum + parseFloat(p.amount_paid || 0), 0);
                                            const total = parseFloat(invoice.total_amount || 0);
                                            const balance = total - paid;
                                            const status = balance <= 0 ? 'paid' : 'pending';
                                            return (
                                                <tr key={invoice.id} className="hover:bg-gray-50">
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm font-medium text-gray-900">{invoice.invoice_number}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-900">{invoice.lease?.shop?.shop_number || '—'}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-900">{invoice.lease?.tenant?.name || '—'}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right text-gray-900">{formatCurrency(total)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right text-green-700">{formatCurrency(paid)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right font-medium text-gray-900">{formatCurrency(balance)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-center">
                                                        <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                                                            status === 'paid' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'
                                                        }`}>
                                                            {status === 'paid' ? 'Paid' : 'Pending'}
                                                        </span>
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                        {invoices.length === 0 && (
                                            <tr>
                                                <td colSpan="7" className="px-4 py-4 text-center text-sm text-gray-500">No invoices found for this month.</td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
