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

const statusConfig = {
    paid: { label: 'Paid ✓', bg: 'bg-green-50', text: 'text-green-800', badge: 'bg-green-100 text-green-800' },
    pending: { label: 'Pending ⏳', bg: 'bg-yellow-50', text: 'text-yellow-800', badge: 'bg-yellow-100 text-yellow-800' },
    overdue: { label: 'Overdue ✗', bg: 'bg-red-50', text: 'text-red-800', badge: 'bg-red-100 text-red-800' },
    no_invoice: { label: 'No Invoice', bg: 'bg-gray-50', text: 'text-gray-500', badge: 'bg-gray-100 text-gray-500' },
};

export default function PaymentTracker({ shops, month }) {
    const [currentMonth, setCurrentMonth] = useState(month || new Date().toISOString().slice(0, 7));

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

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

            <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>

                    {/* Legend */}
                    <div className="flex flex-wrap gap-4 px-2">
                        {Object.entries(statusConfig).map(([key, cfg]) => (
                            <div key={key} className="flex items-center gap-1.5">
                                <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${cfg.badge}`}>{cfg.label}</span>
                            </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">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 Amount</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">
                                        {shops.map((item, idx) => {
                                            const cfg = statusConfig[item.status] || statusConfig.no_invoice;
                                            const balance = (parseFloat(item.invoice?.total_amount) || 0) - (parseFloat(item.total_paid) || 0);
                                            return (
                                                <tr key={idx} className={cfg.bg}>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm font-medium text-gray-900">{item.shop?.shop_number || '—'}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-900">{item.shop?.active_lease?.tenant?.name || '—'}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right text-gray-900">{item.invoice ? formatCurrency(item.invoice.total_amount) : '—'}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right text-gray-900">{formatCurrency(item.total_paid)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right font-medium text-gray-900">{item.invoice ? 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 ${cfg.badge}`}>
                                                            {cfg.label}
                                                        </span>
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                        {shops.length === 0 && (
                                            <tr>
                                                <td colSpan="6" className="px-4 py-4 text-center text-sm text-gray-500">No shops found.</td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
