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

export default function Index({ invoices, filters }) {
    const [showBulk, setShowBulk] = useState(false);
    const bulkForm = useForm({ month: '', due_date: '' });
    const [deleteId, setDeleteId] = useState(null);
    const [deleting, setDeleting] = useState(false);

    const applyFilters = (newFilters) => {
        router.get(route('invoices.index'), { ...filters, ...newFilters }, { preserveState: true, replace: true });
    };

    const handleDelete = () => {
        setDeleting(true);
        router.delete(route('invoices.destroy', deleteId), {
            onFinish: () => { setDeleting(false); setDeleteId(null); },
        });
    };

    const handleBulkGenerate = (e) => {
        e.preventDefault();
        bulkForm.post(route('invoices.generate-bulk'), {
            onSuccess: () => {
                setShowBulk(false);
                bulkForm.reset();
            },
        });
    };

    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-2.5 py-0.5 text-xs font-medium ${styles[status] || styles.pending}`}>
                {status.charAt(0).toUpperCase() + status.slice(1)}
            </span>
        );
    };

    const getPaid = (invoice) => {
        return (invoice.payments || []).reduce((sum, p) => sum + parseFloat(p.amount_paid || 0), 0);
    };

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

            <div className="py-12">
                <div className="mx-auto max-w-7xl sm:px-6 lg:px-8">
                    <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            {/* Header */}
                            <div className="flex items-center justify-between mb-6">
                                <h3 className="text-lg font-medium">All Invoices</h3>
                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => setShowBulk(!showBulk)}
                                        className="inline-flex items-center rounded-md bg-green-600 px-4 py-2 text-sm font-medium text-white hover:bg-green-700"
                                    >
                                        Bulk Generate
                                    </button>
                                    <Link
                                        href={route('invoices.create')}
                                        className="inline-flex items-center rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
                                    >
                                        Generate Invoice
                                    </Link>
                                </div>
                            </div>

                            {/* Bulk Generate Form */}
                            {showBulk && (
                                <div className="mb-6 rounded-lg border border-green-200 bg-green-50 p-4">
                                    <h4 className="text-sm font-medium text-green-800 mb-3">Bulk Generate Invoices</h4>
                                    <form onSubmit={handleBulkGenerate} className="flex items-end gap-4">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Month <span className="text-red-500">*</span></label>
                                            <input
                                                type="month"
                                                value={bulkForm.data.month}
                                                onChange={(e) => bulkForm.setData('month', e.target.value)}
                                                className="mt-1 block rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                            />
                                            {bulkForm.errors.month && <p className="mt-1 text-sm text-red-600">{bulkForm.errors.month}</p>}
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Due Date <span className="text-red-500">*</span></label>
                                            <input
                                                type="date"
                                                value={bulkForm.data.due_date}
                                                onChange={(e) => bulkForm.setData('due_date', e.target.value)}
                                                className="mt-1 block rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                            />
                                            {bulkForm.errors.due_date && <p className="mt-1 text-sm text-red-600">{bulkForm.errors.due_date}</p>}
                                        </div>
                                        <button
                                            type="submit"
                                            disabled={bulkForm.processing}
                                            className="inline-flex items-center rounded-md bg-green-600 px-4 py-2 text-sm font-medium text-white hover:bg-green-700 disabled:opacity-50"
                                        >
                                            {bulkForm.processing ? 'Generating...' : 'Generate All'}
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => setShowBulk(false)}
                                            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"
                                        >
                                            Cancel
                                        </button>
                                    </form>
                                </div>
                            )}

                            {/* Filters */}
                            <div className="mb-6 flex flex-wrap items-center gap-4">
                                <input
                                    type="text"
                                    placeholder="Search by invoice#, tenant..."
                                    defaultValue={filters.search}
                                    onChange={(e) => applyFilters({ search: e.target.value })}
                                    className="w-full max-w-xs rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                />
                                <select
                                    defaultValue={filters.status || ''}
                                    onChange={(e) => applyFilters({ status: e.target.value })}
                                    className="rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                >
                                    <option value="">All Statuses</option>
                                    <option value="pending">Pending</option>
                                    <option value="paid">Paid</option>
                                    <option value="partial">Partial</option>
                                    <option value="overdue">Overdue</option>
                                </select>
                                <input
                                    type="month"
                                    defaultValue={filters.month || ''}
                                    onChange={(e) => applyFilters({ month: e.target.value })}
                                    className="rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                />
                            </div>

                            {/* Table */}
                            <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">Month</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-left text-xs font-medium uppercase tracking-wider text-gray-500">Shop#</th>
                                            <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">Rent</th>
                                            <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">Electricity</th>
                                            <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">Maintenance</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-left text-xs font-medium uppercase tracking-wider text-gray-500">Status</th>
                                            <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-200 bg-white">
                                        {invoices.data.map((invoice) => {
                                            const paid = getPaid(invoice);
                                            const balance = parseFloat(invoice.total_amount) - paid;
                                            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-500">{formatMonth(invoice.month)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-500">{invoice.lease?.tenant?.name || '—'}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-500">{invoice.lease?.shop?.shop_number || '—'}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right text-gray-500">{formatCurrency(invoice.rent_amount)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right text-gray-500">{formatCurrency(invoice.electricity_amount)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right text-gray-500">{formatCurrency(invoice.maintenance_amount)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right font-medium text-gray-900">{formatCurrency(invoice.total_amount)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right text-green-600">{formatCurrency(paid)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm text-right text-red-600">{formatCurrency(balance)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm">{statusBadge(invoice.status)}</td>
                                                    <td className="whitespace-nowrap px-4 py-4 text-sm space-x-2">
                                                        <Link href={route('invoices.show', invoice.id)} className="text-blue-600 hover:text-blue-900">View</Link>
                                                        <Link href={route('invoices.print', invoice.id)} className="text-indigo-600 hover:text-indigo-900">Print</Link>
                                                        <button onClick={() => setDeleteId(invoice.id)} className="text-red-600 hover:text-red-900">Delete</button>
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                        {invoices.data.length === 0 && (
                                            <tr>
                                                <td colSpan="12" className="px-4 py-4 text-center text-sm text-gray-500">No invoices found.</td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>

                            {/* Pagination */}
                            {invoices.links && invoices.links.length > 3 && (
                                <div className="flex flex-wrap items-center gap-1 mt-4">
                                    {invoices.links.map((link, i) => (
                                        link.url ? (
                                            <Link key={i} href={link.url} className={`px-3 py-1 text-sm rounded ${link.active ? 'bg-blue-600 text-white' : 'bg-white border hover:bg-gray-50'}`}
                                                dangerouslySetInnerHTML={{ __html: link.label }} preserveState />
                                        ) : (
                                            <span key={i} className="px-3 py-1 text-sm text-gray-400" dangerouslySetInnerHTML={{ __html: link.label }} />
                                        )
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>

            <ConfirmDeleteModal
                show={deleteId !== null}
                onClose={() => setDeleteId(null)}
                onConfirm={handleDelete}
                title="Delete Invoice"
                message="Are you sure you want to delete this invoice? All payment records for this invoice will also be removed."
                processing={deleting}
            />
        </AuthenticatedLayout>
    );
}
