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

function ActionDropdown({ lease, onRecordPayment, onDeleteLease, isAdmin }) {
    const [open, setOpen] = useState(false);
    const ref = useRef(null);

    useEffect(() => {
        const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, []);

    const hasCommission = lease.commission_paid && parseFloat(lease.commission_amount) > 0;
    const invoices = lease.invoices || [];

    return (
        <div ref={ref} className="relative inline-block text-left">
            <button
                onClick={() => setOpen(!open)}
                className="inline-flex items-center gap-1 rounded-md bg-gray-100 px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-200 transition-colors"
            >
                Actions
                <svg className={`h-4 w-4 transition-transform ${open ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
                </svg>
            </button>

            {open && (
                <div className="absolute right-0 z-50 mt-1 w-56 origin-top-right rounded-lg bg-white shadow-lg ring-1 ring-black/10 divide-y divide-gray-100" style={{ maxHeight: '320px', overflowY: 'auto' }}>
                    {/* Navigation */}
                    <div className="py-1">
                        <p className="px-3 py-1 text-[10px] font-semibold text-gray-400 uppercase tracking-wider">Navigation</p>
                        <Link href={route('leases.show', lease.id)} onClick={() => setOpen(false)} className="flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-blue-50 hover:text-blue-700">
                            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z" /><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" /></svg>
                            View Details
                        </Link>
                        <Link href={route('leases.edit', lease.id)} onClick={() => setOpen(false)} className="flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-indigo-50 hover:text-indigo-700">
                            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931zm0 0L19.5 7.125" /></svg>
                            Edit Lease
                        </Link>
                    </div>

                    {/* Receipts */}
                    <div className="py-1">
                        <p className="px-3 py-1 text-[10px] font-semibold text-gray-400 uppercase tracking-wider">Receipts</p>
                        {hasCommission && (
                            <Link href={route('leases.commission-receipt', lease.id)} target="_blank" onClick={() => setOpen(false)} className="flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-emerald-50 hover:text-emerald-700">
                                <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M6.72 13.829c-.24.03-.48.062-.72.096m.72-.096a42.415 42.415 0 0 1 10.56 0m-10.56 0L6.34 18m10.94-4.171c.24.03.48.062.72.096m-.72-.096L17.66 18m0 0 .229 2.523a1.125 1.125 0 0 1-1.12 1.227H7.231c-.662 0-1.18-.568-1.12-1.227L6.34 18m11.318 0h1.091A2.25 2.25 0 0 0 21 15.75V9.456c0-1.081-.768-2.015-1.837-2.175a48.055 48.055 0 0 0-1.913-.247M6.34 18H5.25A2.25 2.25 0 0 1 3 15.75V9.456c0-1.081.768-2.015 1.837-2.175a48.041 48.041 0 0 1 1.913-.247m10.5 0a48.536 48.536 0 0 0-10.5 0m10.5 0V3.375c0-.621-.504-1.125-1.125-1.125h-8.25c-.621 0-1.125.504-1.125 1.125v3.659M18.75 7.131a48.041 48.041 0 0 0-1.913-.247M6.75 7.131a48.041 48.041 0 0 1-1.913-.247" /></svg>
                                Commission Receipt
                            </Link>
                        )}
                        {!hasCommission && lease.commission_type && lease.commission_type !== 'none' && (
                            <p className="px-3 py-2 text-xs text-gray-400 italic">Commission not paid yet</p>
                        )}
                    </div>

                    {/* Invoices */}
                    {invoices.length > 0 && (
                        <div className="py-1">
                            <p className="px-3 py-1 text-[10px] font-semibold text-gray-400 uppercase tracking-wider">Payments</p>
                            <button
                                onClick={() => { onRecordPayment(lease); setOpen(false); }}
                                className="flex w-full items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-green-50 hover:text-green-700"
                            >
                                <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M2.25 18.75a60.07 60.07 0 0 1 15.797 2.101c.727.198 1.453-.342 1.453-1.096V18.75M3.75 4.5v.75A.75.75 0 0 1 3 6h-.75m0 0v-.375c0-.621.504-1.125 1.125-1.125H20.25M2.25 6v9m18-10.5v.75c0 .414.336.75.75.75h.75m-1.5-1.5h.375c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-.375m1.5-1.5H21a.75.75 0 0 0-.75.75v.75m0 0H3.75m0 0h-.375a1.125 1.125 0 0 1-1.125-1.125V15m1.5 1.5v-.75A.75.75 0 0 0 3 15h-.75M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Zm3 0h.008v.008H18V10.5Zm-12 0h.008v.008H6V10.5Z" /></svg>
                                Record Payment
                            </button>
                        </div>
                    )}

                    {/* Invoices */}
                    {invoices.length > 0 && (
                        <div className="py-1">
                            <p className="px-3 py-1 text-[10px] font-semibold text-gray-400 uppercase tracking-wider">Invoices ({invoices.length})</p>
                            {invoices.slice(0, 6).map((inv) => (
                                <Link key={inv.id} href={route('invoices.print', inv.id)} target="_blank" onClick={() => setOpen(false)} className="flex items-center justify-between gap-2 px-3 py-1.5 text-sm text-gray-700 hover:bg-blue-50 hover:text-blue-700 group">
                                    <span className="flex items-center gap-2">
                                        <svg className="h-3.5 w-3.5 text-gray-400 group-hover:text-blue-500" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" /></svg>
                                        <span className="truncate">{inv.invoice_number}</span>
                                    </span>
                                    <span className="flex items-center gap-1.5">
                                        <span className="text-[10px] text-gray-400">{formatMonth(inv.month)}</span>
                                        <span className={`inline-block h-1.5 w-1.5 rounded-full ${inv.status === 'paid' ? 'bg-green-400' : inv.status === 'partial' ? 'bg-amber-400' : 'bg-red-400'}`} />
                                    </span>
                                </Link>
                            ))}
                            {invoices.length > 6 && (
                                <Link href={route('leases.show', lease.id)} onClick={() => setOpen(false)} className="flex items-center gap-2 px-3 py-1.5 text-xs text-blue-600 hover:text-blue-800 hover:bg-blue-50">
                                    View all {invoices.length} invoices →
                                </Link>
                            )}
                        </div>
                    )}

                    {invoices.length === 0 && (
                        <div className="py-1">
                            <p className="px-3 py-2 text-xs text-gray-400 italic">No invoices generated</p>
                        </div>
                    )}

                    {/* Danger Zone - Admin Only */}
                    {isAdmin && (
                        <div className="py-1">
                            <p className="px-3 py-1 text-[10px] font-semibold text-red-400 uppercase tracking-wider">Danger Zone</p>
                            <button
                                onClick={() => { onDeleteLease(lease); setOpen(false); }}
                                className="flex w-full items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-red-50 hover:text-red-700"
                            >
                                <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" /></svg>
                                Delete Lease
                            </button>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}

export default function Index({ leases, filters }) {
    const { auth } = usePage().props;
    const [paymentLease, setPaymentLease] = useState(null);
    const [deleteLease, setDeleteLease] = useState(null);
    const [deleting, setDeleting] = useState(false);

    const handleDelete = () => {
        if (!deleteLease) return;
        setDeleting(true);
        router.delete(route('leases.destroy', deleteLease.id), {
            onSuccess: () => { setDeleteLease(null); setDeleting(false); },
            onError: () => setDeleting(false),
        });
    };

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

    const statusBadge = (status) => {
        const styles = {
            active: 'bg-green-100 text-green-800',
            expired: 'bg-gray-100 text-gray-800',
            terminated: 'bg-red-100 text-red-800',
        };
        return styles[status] || 'bg-gray-100 text-gray-800';
    };

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

            <div className="py-12">
                <div className="mx-auto max-w-7xl sm:px-6 lg:px-8">
                    <div className="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 Leases</h3>
                                <Link
                                    href={route('leases.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"
                                >
                                    Create Lease
                                </Link>
                            </div>

                            {/* Filters */}
                            <div className="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2">
                                <input
                                    type="text"
                                    placeholder="Search by shop, tenant, owner..."
                                    defaultValue={filters.search}
                                    onChange={(e) => applyFilters({ search: e.target.value })}
                                    className="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 Status</option>
                                    <option value="active">Active</option>
                                    <option value="expired">Expired</option>
                                    <option value="terminated">Terminated</option>
                                </select>
                            </div>

                            {/* Table */}
                            <div className="overflow-x-visible">
                                <table className="min-w-full divide-y divide-gray-200">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Shop #</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Tenant</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Owner</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Agreed Rent</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Initial Rent</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Start Date</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Status</th>
                                            <th className="px-6 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">
                                        {leases.data.map((lease) => (
                                            <tr key={lease.id} className="hover:bg-gray-50">
                                                <td className="whitespace-nowrap px-6 py-4 text-sm font-medium text-gray-900">
                                                    {lease.shop?.shop_number}
                                                </td>
                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                    {lease.tenant?.name}
                                                </td>
                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                    {lease.shop?.owner?.name}
                                                </td>
                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                    {formatCurrency(lease.agreed_rent)}
                                                </td>
                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                    {lease.initial_rent ? formatCurrency(lease.initial_rent) : '—'}
                                                </td>
                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                    {formatDate(lease.start_date)}
                                                </td>
                                                <td className="whitespace-nowrap px-6 py-4 text-sm">
                                                    <span className={`inline-flex rounded-full px-2 text-xs font-semibold leading-5 ${statusBadge(lease.status)}`}>
                                                        {lease.status.charAt(0).toUpperCase() + lease.status.slice(1)}
                                                    </span>
                                                </td>
                                                <td className="whitespace-nowrap px-6 py-4 text-sm">
                                                    <ActionDropdown lease={lease} onRecordPayment={(l) => setPaymentLease(l)} onDeleteLease={(l) => setDeleteLease(l)} isAdmin={auth.user.is_admin} />
                                                </td>
                                            </tr>
                                        ))}
                                        {leases.data.length === 0 && (
                                            <tr>
                                                <td colSpan="8" className="px-6 py-4 text-center text-sm text-gray-500">No leases found.</td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>

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

            <PaymentModal
                show={!!paymentLease}
                onClose={() => setPaymentLease(null)}
                lease={paymentLease}
            />

            <ConfirmDeleteModal
                show={!!deleteLease}
                onClose={() => setDeleteLease(null)}
                onConfirm={handleDelete}
                processing={deleting}
                title="Delete Lease"
                message={deleteLease ? `Are you sure you want to delete the lease for Shop #${deleteLease.shop?.shop_number} (${deleteLease.tenant?.name})? This will mark the shop as vacant. All related invoices and payments will also be removed. This action cannot be undone.` : ''}
            />
        </AuthenticatedLayout>
    );
}
