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

export default function Index({ payments, filters, invoices }) {
    const { auth } = usePage().props;
    const [showAddModal, setShowAddModal] = useState(false);
    const [selectedInvoice, setSelectedInvoice] = useState(null);
    const [deleteId, setDeleteId] = useState(null);
    const [deleting, setDeleting] = useState(false);

    const payForm = useForm({
        invoice_id: '',
        amount_paid: '',
        payment_date: new Date().toISOString().split('T')[0],
        payment_method: 'cash',
        proof_file: null,
        received_by: '',
        remarks: '',
    });

    useEffect(() => {
        if (payForm.data.invoice_id) {
            const inv = invoices.find(i => i.id == payForm.data.invoice_id);
            setSelectedInvoice(inv || null);
        } else {
            setSelectedInvoice(null);
        }
    }, [payForm.data.invoice_id]);

    const getAlreadyPaid = (inv) => (inv?.payments || []).reduce((sum, p) => sum + parseFloat(p.amount_paid || 0), 0);
    const alreadyPaid = selectedInvoice ? getAlreadyPaid(selectedInvoice) : 0;
    const totalAmount = selectedInvoice ? parseFloat(selectedInvoice.total_amount || 0) : 0;
    const remainingBalance = totalAmount - alreadyPaid;

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

    const openAddModal = () => {
        payForm.reset();
        setSelectedInvoice(null);
        setShowAddModal(true);
    };

    const handleRecord = (e) => {
        e.preventDefault();
        payForm.post(route('payments.store'), {
            forceFormData: true,
            onSuccess: () => { setShowAddModal(false); payForm.reset(); setSelectedInvoice(null); },
        });
    };

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

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

            <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 Payments</h3>
                                <button
                                    onClick={openAddModal}
                                    className="inline-flex items-center rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
                                >
                                    + Record Payment
                                </button>
                            </div>

                            {/* Filters */}
                            <div className="mb-6">
                                <input
                                    type="text"
                                    placeholder="Search by tenant name..."
                                    defaultValue={filters.search}
                                    onChange={(e) => applyFilters({ search: e.target.value })}
                                    className="w-full max-w-md 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">Date</th>
                                            <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">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">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-200 bg-white">
                                        {payments.data.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-gray-500">
                                                    {payment.invoice ? (
                                                        <Link href={route('invoices.show', payment.invoice.id)} className="text-blue-600 hover:text-blue-900">
                                                            {payment.invoice.invoice_number}
                                                        </Link>
                                                    ) : '—'}
                                                </td>
                                                <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-500">{payment.invoice?.lease?.shop?.shop_number || '—'}</td>
                                                <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-900">{payment.invoice?.lease?.tenant?.name || '—'}</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 space-x-2">
                                                    <Link href={route('payments.show', payment.id)} className="text-blue-600 hover:text-blue-900">View</Link>
                                                    {auth.user.is_admin && (
                                                    <button onClick={() => setDeleteId(payment.id)} className="text-red-600 hover:text-red-900">Delete</button>
                                                    )}
                                                </td>
                                            </tr>
                                        ))}
                                        {payments.data.length === 0 && (
                                            <tr>
                                                <td colSpan="7" className="px-4 py-4 text-center text-sm text-gray-500">No payments found.</td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>

                            {/* Pagination */}
                            {payments.links && payments.links.length > 3 && (
                                <div className="flex flex-wrap items-center gap-1 mt-4">
                                    {payments.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>

            {/* Record Payment Modal */}
            <FormModal show={showAddModal} onClose={() => setShowAddModal(false)} title="Record Payment" maxWidth="2xl">
                <form onSubmit={handleRecord} className="space-y-4">
                    {/* Invoice Select */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700">Invoice *</label>
                        <select
                            value={payForm.data.invoice_id}
                            onChange={(e) => payForm.setData('invoice_id', e.target.value)}
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                        >
                            <option value="">Select an invoice...</option>
                            {invoices.map((inv) => {
                                const paid = getAlreadyPaid(inv);
                                const balance = parseFloat(inv.total_amount || 0) - paid;
                                return (
                                    <option key={inv.id} value={inv.id}>
                                        {inv.invoice_number} - Shop #{inv.lease?.shop?.shop_number} - {inv.lease?.tenant?.name} - Balance: PKR {balance.toLocaleString()}
                                    </option>
                                );
                            })}
                        </select>
                        {payForm.errors.invoice_id && <p className="mt-1 text-sm text-red-600">{payForm.errors.invoice_id}</p>}
                    </div>

                    {/* Invoice Info Box */}
                    {selectedInvoice && (
                        <div className="rounded-md bg-blue-50 border border-blue-200 p-4">
                            <div className="grid grid-cols-3 gap-4 text-sm">
                                <div>
                                    <span className="text-gray-500">Total Amount</span>
                                    <p className="font-semibold text-gray-900">{formatCurrency(totalAmount)}</p>
                                </div>
                                <div>
                                    <span className="text-gray-500">Already Paid</span>
                                    <p className="font-semibold text-green-600">{formatCurrency(alreadyPaid)}</p>
                                </div>
                                <div>
                                    <span className="text-gray-500">Remaining Balance</span>
                                    <p className="font-semibold text-red-600">{formatCurrency(remainingBalance)}</p>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* Amount */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700">Amount Paid *</label>
                        <input
                            type="number"
                            step="0.01"
                            value={payForm.data.amount_paid}
                            onChange={(e) => payForm.setData('amount_paid', e.target.value)}
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                        />
                        {payForm.errors.amount_paid && <p className="mt-1 text-sm text-red-600">{payForm.errors.amount_paid}</p>}
                    </div>

                    {/* Date + Method */}
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-700">Payment Date *</label>
                            <input
                                type="date"
                                value={payForm.data.payment_date}
                                onChange={(e) => payForm.setData('payment_date', e.target.value)}
                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                            />
                            {payForm.errors.payment_date && <p className="mt-1 text-sm text-red-600">{payForm.errors.payment_date}</p>}
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700">Payment Method *</label>
                            <select
                                value={payForm.data.payment_method}
                                onChange={(e) => payForm.setData('payment_method', e.target.value)}
                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                            >
                                <option value="cash">Cash</option>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="cheque">Cheque</option>
                            </select>
                            {payForm.errors.payment_method && <p className="mt-1 text-sm text-red-600">{payForm.errors.payment_method}</p>}
                        </div>
                    </div>

                    {/* Proof File */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700">Proof File</label>
                        <input
                            type="file"
                            onChange={(e) => payForm.setData('proof_file', e.target.files[0])}
                            className="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
                        />
                        {payForm.errors.proof_file && <p className="mt-1 text-sm text-red-600">{payForm.errors.proof_file}</p>}
                    </div>

                    {/* Received By + Remarks */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700">Received By</label>
                        <input
                            type="text"
                            value={payForm.data.received_by}
                            onChange={(e) => payForm.setData('received_by', e.target.value)}
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                        />
                        {payForm.errors.received_by && <p className="mt-1 text-sm text-red-600">{payForm.errors.received_by}</p>}
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700">Remarks</label>
                        <textarea
                            rows={2}
                            value={payForm.data.remarks}
                            onChange={(e) => payForm.setData('remarks', e.target.value)}
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                        />
                        {payForm.errors.remarks && <p className="mt-1 text-sm text-red-600">{payForm.errors.remarks}</p>}
                    </div>

                    {/* Submit */}
                    <div className="flex justify-end gap-3 pt-2">
                        <button type="button" onClick={() => setShowAddModal(false)} className="rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                            Cancel
                        </button>
                        <button type="submit" disabled={payForm.processing} className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50">
                            {payForm.processing ? 'Saving...' : 'Record Payment'}
                        </button>
                    </div>
                </form>
            </FormModal>

            {/* Confirm Delete Modal */}
            <ConfirmDeleteModal
                show={!!deleteId}
                onClose={() => { setDeleteId(null); setDeleting(false); }}
                onConfirm={handleDelete}
                title="Delete Payment"
                message="Are you sure you want to delete this payment? This action cannot be undone."
                processing={deleting}
            />
        </AuthenticatedLayout>
    );
}
