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

export default function Show({ lease }) {
    const { auth } = usePage().props;
    const [showDepositForm, setShowDepositForm] = useState(false);
    const [showTerminate, setShowTerminate] = useState(false);
    const [terminating, setTerminating] = useState(false);
    const [payingCommission, setPayingCommission] = useState(false);
    const [showRenewalForm, setShowRenewalForm] = useState(false);

    // Renewal form helpers
    const parseDate = (dateStr) => {
        const [y, m, d] = dateStr.split('-').map(Number);
        return new Date(y, m - 1, d);
    };
    const formatYMD = (d) => {
        const y = d.getFullYear();
        const m = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${y}-${m}-${day}`;
    };
    const addDays = (dateStr, days) => {
        if (!dateStr) return '';
        const d = parseDate(dateStr);
        d.setDate(d.getDate() + parseInt(days || 0));
        return formatYMD(d);
    };
    const addMonthsHelper = (dateStr, months) => {
        if (!dateStr || !months) return '';
        const d = parseDate(dateStr);
        d.setMonth(d.getMonth() + parseInt(months));
        d.setDate(d.getDate() - 1);
        return formatYMD(d);
    };

    // Calculate increased rent for renewal
    const calcRenewalRent = () => {
        const base = parseFloat(lease.agreed_rent) || 0;
        if (lease.annual_increase_type === 'percentage') {
            return Math.round(base * (1 + parseFloat(lease.annual_increase_value || 0) / 100));
        }
        return base + parseFloat(lease.annual_increase_value || 0);
    };

    // Default renewal start = day after lease end
    const renewalDefaultStart = () => {
        if (lease.end_date) {
            return addDays(lease.end_date.split('T')[0], 1);
        }
        return new Date().toISOString().split('T')[0];
    };

    const renewalForm = useForm({
        start_date: renewalDefaultStart(),
        grace_days: 0,
        lease_duration: '11',
        end_date: addMonthsHelper(renewalDefaultStart(), '11'),
        agreed_rent: calcRenewalRent(),
        annual_increase_type: lease.annual_increase_type || 'percentage',
        annual_increase_value: lease.annual_increase_value || '10',
    });

    const handleRenewalMoveInChange = (moveIn) => {
        const grace = parseInt(renewalForm.data.grace_days) || 0;
        const rentStart = addDays(moveIn, grace);
        const dur = renewalForm.data.lease_duration;
        const endDate = dur !== 'custom' ? addMonthsHelper(rentStart, dur) : renewalForm.data.end_date;
        renewalForm.setData(prev => ({ ...prev, start_date: rentStart, end_date: endDate }));
    };

    const handleRenewalDurationChange = (duration) => {
        if (duration === 'custom') {
            renewalForm.setData(prev => ({ ...prev, lease_duration: duration }));
        } else {
            const endDate = addMonthsHelper(renewalForm.data.start_date, duration);
            renewalForm.setData(prev => ({ ...prev, lease_duration: duration, end_date: endDate }));
        }
    };

    const handleRenewalSubmit = (e) => {
        e.preventDefault();
        renewalForm.post(route('leases.renew', lease.id), {
            onSuccess: () => setShowRenewalForm(false),
        });
    };

    // Check lease expiry status
    const isExpiringSoon = () => {
        if (!lease.end_date || lease.status !== 'active') return false;
        const end = new Date(lease.end_date);
        const now = new Date();
        const daysLeft = Math.ceil((end - now) / (1000 * 60 * 60 * 24));
        return daysLeft <= 30 && daysLeft > 0;
    };

    const isExpired = () => {
        if (!lease.end_date) return false;
        return new Date(lease.end_date) < new Date() && lease.status === 'active';
    };

    const daysUntilExpiry = () => {
        if (!lease.end_date) return null;
        return Math.ceil((new Date(lease.end_date) - new Date()) / (1000 * 60 * 60 * 24));
    };

    // Lease duration for summary
    const leaseDuration = () => {
        if (!lease.start_date || !lease.end_date) return null;
        const start = new Date(lease.start_date);
        const end = new Date(lease.end_date);
        const months = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth());
        const days = end.getDate() - start.getDate();
        return { months, days: days >= 0 ? days : 0 };
    };

    const depositForm = useForm({
        amount: '',
        payment_date: '',
        payment_method: 'cash',
        proof_file: null,
        remarks: '',
        received_by: '',
    });

    const handleDepositSubmit = (e) => {
        e.preventDefault();
        depositForm.post(route('leases.deposit', lease.id), {
            forceFormData: true,
            onSuccess: () => {
                setShowDepositForm(false);
                depositForm.reset();
            },
        });
    };

    const handleTerminate = () => {
        setTerminating(true);
        router.post(route('leases.terminate', lease.id), {}, {
            onFinish: () => { setTerminating(false); setShowTerminate(false); },
        });
    };

    const handlePayCommission = () => {
        setPayingCommission(true);
        router.post(route('leases.pay-commission', lease.id), {}, {
            onFinish: () => setPayingCommission(false),
        });
    };

    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';
    };

    const depositTotal = parseFloat(lease.agreed_security_deposit) || 0;
    const depositPaid = parseFloat(lease.security_deposit_paid) || 0;
    const depositRemaining = depositTotal - depositPaid;
    const depositPercentage = depositTotal > 0 ? Math.min((depositPaid / depositTotal) * 100, 100) : 0;

    return (
        <AuthenticatedLayout header={<h2 className="text-xl font-semibold leading-tight text-gray-800">Lease Details</h2>}>
            <Head title={`Lease - Shop #${lease.shop?.shop_number}`} />

            <div className="py-12">
                <div className="mx-auto max-w-7xl sm:px-6 lg:px-8 space-y-6">
                    {/* Action Buttons */}
                    <div className="flex items-center justify-between">
                        <Link href={route('leases.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 Leases
                        </Link>
                        <div className="space-x-2">
                            {auth.user.is_admin && (
                            <Link href={route('leases.edit', lease.id)} className="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">
                                Edit Lease
                            </Link>
                            )}
                            {auth.user.is_admin && lease.status === 'active' && (
                                <button
                                    onClick={() => setShowTerminate(true)}
                                    className="inline-flex items-center rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700"
                                >
                                    Terminate Lease
                                </button>
                            )}
                        </div>
                    </div>

                    {/* Expiry Warning Banner */}
                    {isExpired() && (
                        <div className="rounded-lg border-2 border-red-300 bg-red-50 p-4 flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <div className="flex-shrink-0 h-10 w-10 rounded-full bg-red-100 flex items-center justify-center">
                                    <svg className="h-5 w-5 text-red-600" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z" /></svg>
                                </div>
                                <div>
                                    <p className="text-sm font-semibold text-red-800">Lease Expired!</p>
                                    <p className="text-xs text-red-700">This lease expired {Math.abs(daysUntilExpiry())} days ago. Renew it to continue.</p>
                                </div>
                            </div>
                            {auth.user.is_admin && (
                                <button onClick={() => setShowRenewalForm(true)} className="inline-flex items-center rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700">
                                    Renew Now
                                </button>
                            )}
                        </div>
                    )}

                    {isExpiringSoon() && (
                        <div className="rounded-lg border-2 border-amber-300 bg-amber-50 p-4 flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <div className="flex-shrink-0 h-10 w-10 rounded-full bg-amber-100 flex items-center justify-center">
                                    <svg className="h-5 w-5 text-amber-600" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>
                                </div>
                                <div>
                                    <p className="text-sm font-semibold text-amber-800">Lease Expiring Soon!</p>
                                    <p className="text-xs text-amber-700">{daysUntilExpiry()} days remaining until lease expires on {formatDate(lease.end_date)}.</p>
                                </div>
                            </div>
                            {auth.user.is_admin && (
                                <button onClick={() => setShowRenewalForm(true)} className="inline-flex items-center rounded-md bg-amber-600 px-4 py-2 text-sm font-medium text-white hover:bg-amber-700">
                                    Renew Lease
                                </button>
                            )}
                        </div>
                    )}

                    {/* Lease Summary Card */}
                    <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <div className="flex items-center justify-between mb-6">
                                <h3 className="text-lg font-medium">Lease Summary</h3>
                                <span className={`inline-flex rounded-full px-3 py-1 text-xs font-semibold leading-5 ${statusBadge(lease.status)}`}>
                                    {lease.status.charAt(0).toUpperCase() + lease.status.slice(1)}
                                </span>
                            </div>
                            <dl className="grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2 lg:grid-cols-4">
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Shop #</dt>
                                    <dd className="mt-1 text-sm text-gray-900">{lease.shop?.shop_number}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Owner</dt>
                                    <dd className="mt-1 text-sm text-gray-900">{lease.shop?.owner?.name}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Tenant Name</dt>
                                    <dd className="mt-1 text-sm text-gray-900">{lease.tenant?.name}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Phone</dt>
                                    <dd className="mt-1 text-sm text-gray-900">{lease.tenant?.phone || '—'}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">CNIC</dt>
                                    <dd className="mt-1 text-sm text-gray-900">{lease.tenant?.cnic || '—'}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Move-in Date</dt>
                                    <dd className="mt-1 text-sm text-gray-900">{formatDate(lease.move_in_date)}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Rent Start Date</dt>
                                    <dd className="mt-1 text-sm text-green-700 font-medium">{formatDate(lease.start_date)}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">End Date</dt>
                                    <dd className="mt-1 text-sm text-gray-900">{lease.end_date ? formatDate(lease.end_date) : '—'}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Grace Period</dt>
                                    <dd className="mt-1 text-sm text-gray-900">{lease.grace_days || 0} days free</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Lease Duration</dt>
                                    <dd className="mt-1 text-sm font-medium text-indigo-700">
                                        {leaseDuration()
                                            ? `${leaseDuration().months} months${leaseDuration().days > 0 ? ` ${leaseDuration().days} days` : ''}`
                                            : '—'}
                                    </dd>
                                </div>
                                {lease.status === 'active' && lease.end_date && daysUntilExpiry() > 0 && (
                                    <div>
                                        <dt className="text-sm font-medium text-gray-500">Remaining</dt>
                                        <dd className={`mt-1 text-sm font-medium ${daysUntilExpiry() <= 30 ? 'text-red-600' : 'text-green-600'}`}>
                                            {daysUntilExpiry()} days left
                                        </dd>
                                    </div>
                                )}
                            </dl>
                        </div>
                    </div>

                    {/* Rent Agreement Section */}
                    <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <h3 className="text-lg font-medium mb-4">Rent Agreement</h3>
                            <dl className="grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-3">
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Agreed Rent</dt>
                                    <dd className="mt-1 text-sm text-gray-900">{formatCurrency(lease.agreed_rent)}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Annual Increase</dt>
                                    <dd className="mt-1 text-sm text-gray-900">
                                        {lease.annual_increase_type === 'percentage'
                                            ? `${lease.annual_increase_value}% per year`
                                            : `PKR ${parseFloat(lease.annual_increase_value || 0).toLocaleString()} per year`
                                        }
                                    </dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Current Applicable Rent</dt>
                                    <dd className="mt-1 text-sm font-semibold text-blue-600">
                                        {formatCurrency(lease.current_rent)}
                                        {parseFloat(lease.current_rent) > parseFloat(lease.agreed_rent) && (
                                            <span className="ml-2 text-xs font-normal text-green-600">(increased)</span>
                                        )}
                                        {lease.is_initial_rent_period && lease.initial_rent && (
                                            <span className="ml-2 text-xs font-normal text-gray-500">(discounted)</span>
                                        )}
                                    </dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Initial Rent</dt>
                                    <dd className="mt-1 text-sm text-gray-900">
                                        {lease.initial_rent
                                            ? `${formatCurrency(lease.initial_rent)} (for ${lease.initial_rent_months} months)`
                                            : 'N/A'}
                                    </dd>
                                </div>
                            </dl>
                        </div>
                    </div>

                    {/* Security Deposit Section */}
                    {lease.commission_type && lease.commission_type !== 'none' && (
                        <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                            <div className="p-6 text-gray-900">
                                <div className="flex items-center justify-between mb-4">
                                    <h3 className="text-lg font-medium">Referral Commission</h3>
                                    <span className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold leading-5 ${
                                        lease.commission_paid
                                            ? 'bg-green-100 text-green-800'
                                            : 'bg-amber-100 text-amber-800'
                                    }`}>
                                        <span className={`h-1.5 w-1.5 rounded-full ${lease.commission_paid ? 'bg-green-500' : 'bg-amber-500'}`}></span>
                                        {lease.commission_paid ? 'Paid' : 'Pending'}
                                    </span>
                                </div>
                                <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2 lg:grid-cols-4">
                                    <div>
                                        <dt className="text-sm font-medium text-gray-500">Commission Type</dt>
                                        <dd className="mt-1 text-sm text-gray-900 capitalize">
                                            {lease.commission_type === 'full_rent' ? 'Full Rent (100%)'
                                                : lease.commission_type === 'half_rent' ? 'Half Rent (50%)'
                                                : 'Fixed Amount'}
                                        </dd>
                                    </div>
                                    <div>
                                        <dt className="text-sm font-medium text-gray-500">Commission Amount</dt>
                                        <dd className="mt-1 text-sm font-semibold text-blue-600">{formatCurrency(lease.commission_amount)}</dd>
                                    </div>
                                    <div>
                                        <dt className="text-sm font-medium text-gray-500">Receiver Name</dt>
                                        <dd className="mt-1 text-sm text-gray-900">{lease.commission_to || '—'}</dd>
                                    </div>
                                    <div>
                                        <dt className="text-sm font-medium text-gray-500">Receiver Phone</dt>
                                        <dd className="mt-1 text-sm text-gray-900">{lease.commission_phone || '—'}</dd>
                                    </div>
                                    {lease.commission_paid && lease.commission_paid_date && (
                                        <div>
                                            <dt className="text-sm font-medium text-gray-500">Paid On</dt>
                                            <dd className="mt-1 text-sm text-gray-900">{formatDate(lease.commission_paid_date)}</dd>
                                        </div>
                                    )}
                                    {lease.commission_remarks && (
                                        <div className="sm:col-span-2">
                                            <dt className="text-sm font-medium text-gray-500">Remarks</dt>
                                            <dd className="mt-1 text-sm text-gray-900">{lease.commission_remarks}</dd>
                                        </div>
                                    )}
                                </dl>

                                {!lease.commission_paid && auth.user.is_admin && (
                                    <div className="mt-4 pt-4 border-t">
                                        <button
                                            onClick={handlePayCommission}
                                            disabled={payingCommission}
                                            className="inline-flex items-center rounded-md bg-emerald-600 px-4 py-2 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-50"
                                        >
                                            {payingCommission ? 'Processing...' : `Mark as Paid (${formatCurrency(lease.commission_amount)})`}
                                        </button>
                                    </div>
                                )}

                                {lease.commission_paid && (
                                    <div className="mt-4 pt-4 border-t">
                                        <Link
                                            href={route('leases.commission-receipt', lease.id)}
                                            target="_blank"
                                            className="inline-flex items-center rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
                                        >
                                            <svg className="h-4 w-4 mr-2" 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>
                                            Print Receipt
                                        </Link>
                                    </div>
                                )}
                            </div>
                        </div>
                    )}

                    {/* Security Deposit Section (below commission) */}
                    <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <div className="flex items-center justify-between mb-4">
                                <h3 className="text-lg font-medium">Security Deposit</h3>
                                <button
                                    onClick={() => setShowDepositForm(!showDepositForm)}
                                    className="inline-flex items-center rounded-md bg-green-600 px-4 py-2 text-sm font-medium text-white hover:bg-green-700"
                                >
                                    {showDepositForm ? 'Cancel' : 'Record Deposit'}
                                </button>
                            </div>

                            <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-3 mb-4">
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Total Agreed</dt>
                                    <dd className="mt-1 text-sm text-gray-900">{formatCurrency(depositTotal)}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Total Paid</dt>
                                    <dd className="mt-1 text-sm text-green-600 font-medium">{formatCurrency(depositPaid)}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-medium text-gray-500">Remaining</dt>
                                    <dd className={`mt-1 text-sm font-medium ${depositRemaining > 0 ? 'text-red-600' : 'text-green-600'}`}>
                                        {formatCurrency(depositRemaining)}
                                    </dd>
                                </div>
                            </dl>

                            {/* Progress Bar */}
                            {depositTotal > 0 && (
                                <div className="mb-6">
                                    <div className="flex justify-between text-xs text-gray-500 mb-1">
                                        <span>{Math.round(depositPercentage)}% paid</span>
                                        <span>{formatCurrency(depositTotal)}</span>
                                    </div>
                                    <div className="w-full bg-gray-200 rounded-full h-2.5">
                                        <div
                                            className={`h-2.5 rounded-full ${depositPercentage >= 100 ? 'bg-green-500' : 'bg-blue-500'}`}
                                            style={{ width: `${depositPercentage}%` }}
                                        ></div>
                                    </div>
                                </div>
                            )}

                            {/* Record Deposit Form */}
                            {showDepositForm && (
                                <div className="border rounded-lg p-4 mb-6 bg-gray-50">
                                    <h4 className="text-sm font-medium text-gray-900 mb-4">Record New Deposit Payment</h4>
                                    <form onSubmit={handleDepositSubmit} className="space-y-4">
                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700">Amount (PKR) <span className="text-red-500">*</span></label>
                                                <input
                                                    type="number"
                                                    min="0"
                                                    value={depositForm.data.amount}
                                                    onChange={(e) => depositForm.setData('amount', e.target.value)}
                                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                                />
                                                {depositForm.errors.amount && <p className="mt-1 text-sm text-red-600">{depositForm.errors.amount}</p>}
                                            </div>
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700">Payment Date <span className="text-red-500">*</span></label>
                                                <input
                                                    type="date"
                                                    value={depositForm.data.payment_date}
                                                    onChange={(e) => depositForm.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"
                                                />
                                                {depositForm.errors.payment_date && <p className="mt-1 text-sm text-red-600">{depositForm.errors.payment_date}</p>}
                                            </div>
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700">Payment Method</label>
                                                <select
                                                    value={depositForm.data.payment_method}
                                                    onChange={(e) => depositForm.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>
                                                </select>
                                                {depositForm.errors.payment_method && <p className="mt-1 text-sm text-red-600">{depositForm.errors.payment_method}</p>}
                                            </div>
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700">Proof File</label>
                                                <input
                                                    type="file"
                                                    onChange={(e) => depositForm.setData('proof_file', e.target.files[0])}
                                                    className="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:rounded-md file:border-0 file:bg-blue-50 file:px-4 file:py-2 file:text-sm file:font-medium file:text-blue-700 hover:file:bg-blue-100"
                                                />
                                                {depositForm.errors.proof_file && <p className="mt-1 text-sm text-red-600">{depositForm.errors.proof_file}</p>}
                                            </div>
                                        </div>
                                        {depositForm.data.payment_method === 'cash' && (
                                            <div className="border border-amber-200 rounded-lg p-4 bg-amber-50">
                                                <div className="flex items-center gap-2 mb-3">
                                                    <svg className="h-5 w-5 text-amber-600" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" />
                                                    </svg>
                                                    <h5 className="text-sm font-semibold text-amber-800">Cash Payment - Signature Required</h5>
                                                </div>
                                                <div>
                                                    <label className="block text-sm font-medium text-amber-800">Received By (Name) <span className="text-red-500">*</span></label>
                                                    <input
                                                        type="text"
                                                        value={depositForm.data.received_by}
                                                        onChange={(e) => depositForm.setData('received_by', e.target.value)}
                                                        placeholder="Enter name of person receiving cash..."
                                                        className="mt-1 block w-full rounded-md border-amber-300 shadow-sm focus:border-amber-500 focus:ring-amber-500 bg-white"
                                                    />
                                                    {depositForm.errors.received_by && <p className="mt-1 text-sm text-red-600">{depositForm.errors.received_by}</p>}
                                                    <p className="mt-1 text-xs text-amber-600">This name will appear on the payment receipt for signature verification.</p>
                                                </div>
                                            </div>
                                        )}
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Remarks</label>
                                            <textarea
                                                value={depositForm.data.remarks}
                                                onChange={(e) => depositForm.setData('remarks', e.target.value)}
                                                rows={2}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                            />
                                            {depositForm.errors.remarks && <p className="mt-1 text-sm text-red-600">{depositForm.errors.remarks}</p>}
                                        </div>
                                        <div className="flex justify-end">
                                            <button
                                                type="submit"
                                                disabled={depositForm.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"
                                            >
                                                Save Deposit Payment
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            )}

                            {/* Deposit Payments Table */}
                            {lease.security_deposit_payments && lease.security_deposit_payments.length > 0 && (
                                <div className="overflow-x-auto">
                                    <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">Date</th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Amount</th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Method</th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Received By</th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Proof</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-gray-200 bg-white">
                                            {lease.security_deposit_payments.map((payment) => (
                                                <tr key={payment.id} className="hover:bg-gray-50">
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-900">{formatDate(payment.payment_date)}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-900">{formatCurrency(payment.amount)}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500 capitalize">{payment.payment_method?.replace('_', ' ')}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-900">{payment.received_by || '—'}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm">
                                                        {payment.proof_file ? (
                                                            <a href={`/storage/${payment.proof_file}`} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">
                                                                View
                                                            </a>
                                                        ) : '—'}
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Invoices Table */}
                    <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <h3 className="text-lg font-medium mb-4">Invoices</h3>
                            <div className="overflow-x-auto">
                                <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">Invoice #</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Month</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Rent</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Electricity</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Maintenance</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Total</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Paid</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Balance</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-200 bg-white">
                                        {lease.invoices?.map((invoice) => {
                                            const paidAmount = invoice.payments?.reduce((sum, p) => sum + parseFloat(p.amount || 0), 0) || 0;
                                            const balance = parseFloat(invoice.total_amount || 0) - paidAmount;
                                            return (
                                                <tr key={invoice.id} className="hover:bg-gray-50">
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm font-medium">
                                                        <Link href={route('invoices.show', invoice.id)} className="text-blue-600 hover:text-blue-900">
                                                            {invoice.invoice_number || `#${invoice.id}`}
                                                        </Link>
                                                    </td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">{formatMonth(invoice.month)}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">{formatCurrency(invoice.rent_amount)}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">{formatCurrency(invoice.electricity_amount)}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">{formatCurrency(invoice.maintenance_amount)}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-900 font-medium">{formatCurrency(invoice.total_amount)}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-green-600">{formatCurrency(paidAmount)}</td>
                                                    <td className={`whitespace-nowrap px-6 py-4 text-sm font-medium ${balance > 0 ? 'text-red-600' : 'text-green-600'}`}>
                                                        {formatCurrency(balance)}
                                                    </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 ${
                                                            invoice.status === 'paid' ? 'bg-green-100 text-green-800'
                                                                : invoice.status === 'partial' ? 'bg-yellow-100 text-yellow-800'
                                                                : 'bg-red-100 text-red-800'
                                                        }`}>
                                                            {invoice.status?.charAt(0).toUpperCase() + invoice.status?.slice(1)}
                                                        </span>
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                        {(!lease.invoices || lease.invoices.length === 0) && (
                                            <tr>
                                                <td colSpan="9" className="px-6 py-4 text-center text-sm text-gray-500">No invoices yet.</td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    {/* Meter Readings Table */}
                    {lease.electricity_enabled && (
                        <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                            <div className="p-6 text-gray-900">
                                <h3 className="text-lg font-medium mb-4">Meter Readings</h3>
                                <div className="overflow-x-auto">
                                    <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">Month</th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Previous</th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Current</th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Units</th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Rate</th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Amount</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-gray-200 bg-white">
                                            {lease.meter_readings?.map((reading) => (
                                                <tr key={reading.id} className="hover:bg-gray-50">
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-900">{formatMonth(reading.month)}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">{reading.previous_reading}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">{reading.current_reading}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">{reading.units_consumed}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">{formatCurrency(reading.rate_per_unit)}</td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-900 font-medium">{formatCurrency(reading.total_amount)}</td>
                                                </tr>
                                            ))}
                                            {(!lease.meter_readings || lease.meter_readings.length === 0) && (
                                                <tr>
                                                    <td colSpan="6" className="px-6 py-4 text-center text-sm text-gray-500">No meter readings yet.</td>
                                                </tr>
                                            )}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    )}
                    {/* Lease Renewal Section */}
                    {showRenewalForm && auth.user.is_admin && (
                        <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg border-2 border-emerald-300">
                            <div className="p-6 text-gray-900">
                                <div className="flex items-center justify-between mb-4">
                                    <div className="flex items-center gap-3">
                                        <div className="h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center">
                                            <svg className="h-5 w-5 text-emerald-600" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182" /></svg>
                                        </div>
                                        <div>
                                            <h3 className="text-lg font-semibold text-gray-900">Renew Lease</h3>
                                            <p className="text-xs text-gray-500">Create a new lease with updated terms. Old lease will be marked as expired.</p>
                                        </div>
                                    </div>
                                    <button onClick={() => setShowRenewalForm(false)} className="text-gray-400 hover:text-gray-600">
                                        <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
                                    </button>
                                </div>

                                {/* Previous vs New Rent Comparison */}
                                <div className="mb-6 rounded-lg bg-gradient-to-r from-gray-50 to-emerald-50 border border-emerald-200 p-4">
                                    <p className="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-3">Rent Comparison</p>
                                    <div className="flex items-center gap-4">
                                        <div className="flex-1 text-center rounded-lg bg-white p-3 border">
                                            <p className="text-xs text-gray-500">Previous Rent</p>
                                            <p className="text-lg font-bold text-gray-700">{formatCurrency(lease.agreed_rent)}</p>
                                        </div>
                                        <div className="flex-shrink-0">
                                            <svg className="h-6 w-6 text-emerald-500" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3" /></svg>
                                        </div>
                                        <div className="flex-1 text-center rounded-lg bg-emerald-50 p-3 border border-emerald-200">
                                            <p className="text-xs text-emerald-600">New Rent</p>
                                            <p className="text-lg font-bold text-emerald-700">{formatCurrency(renewalForm.data.agreed_rent)}</p>
                                            {parseFloat(renewalForm.data.agreed_rent) > parseFloat(lease.agreed_rent) && (
                                                <p className="text-xs text-emerald-600">
                                                    +{formatCurrency(parseFloat(renewalForm.data.agreed_rent) - parseFloat(lease.agreed_rent))} increase
                                                </p>
                                            )}
                                        </div>
                                    </div>
                                </div>

                                <form onSubmit={handleRenewalSubmit} className="space-y-4">
                                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Rent Start Date <span className="text-red-500">*</span></label>
                                            <input
                                                type="date"
                                                value={renewalForm.data.start_date}
                                                onChange={(e) => {
                                                    const val = e.target.value;
                                                    const dur = renewalForm.data.lease_duration;
                                                    const endDate = dur !== 'custom' ? addMonthsHelper(val, dur) : renewalForm.data.end_date;
                                                    renewalForm.setData(prev => ({ ...prev, start_date: val, end_date: endDate }));
                                                }}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500"
                                            />
                                            {renewalForm.errors.start_date && <p className="mt-1 text-sm text-red-600">{renewalForm.errors.start_date}</p>}
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Grace Days</label>
                                            <input
                                                type="number"
                                                min="0"
                                                value={renewalForm.data.grace_days}
                                                onChange={(e) => renewalForm.setData('grace_days', e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Duration</label>
                                            <div className="mt-1 flex gap-2">
                                                {[{ value: '6', label: '6M' }, { value: '11', label: '11M' }, { value: '12', label: '12M' }, { value: 'custom', label: 'Custom' }].map((opt) => (
                                                    <button
                                                        key={opt.value}
                                                        type="button"
                                                        onClick={() => handleRenewalDurationChange(opt.value)}
                                                        className={`flex-1 rounded-md px-2 py-2 text-xs font-medium border-2 transition-all ${
                                                            renewalForm.data.lease_duration === opt.value
                                                                ? 'border-emerald-500 bg-emerald-50 text-emerald-700'
                                                                : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300'
                                                        }`}
                                                    >
                                                        {opt.label}
                                                    </button>
                                                ))}
                                            </div>
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">End Date</label>
                                            <input
                                                type="date"
                                                value={renewalForm.data.end_date}
                                                onChange={(e) => renewalForm.setData('end_date', e.target.value)}
                                                readOnly={renewalForm.data.lease_duration !== 'custom'}
                                                className={`mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 ${
                                                    renewalForm.data.lease_duration !== 'custom' ? 'bg-gray-100' : ''
                                                }`}
                                            />
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">New Monthly Rent (PKR) <span className="text-red-500">*</span></label>
                                            <input
                                                type="number"
                                                min="0"
                                                value={renewalForm.data.agreed_rent}
                                                onChange={(e) => renewalForm.setData('agreed_rent', e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500"
                                            />
                                            {renewalForm.errors.agreed_rent && <p className="mt-1 text-sm text-red-600">{renewalForm.errors.agreed_rent}</p>}
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Annual Increase Type</label>
                                            <select
                                                value={renewalForm.data.annual_increase_type}
                                                onChange={(e) => renewalForm.setData('annual_increase_type', e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500"
                                            >
                                                <option value="percentage">Percentage (%)</option>
                                                <option value="fixed">Fixed Amount (PKR)</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">
                                                {renewalForm.data.annual_increase_type === 'percentage' ? 'Increase %' : 'Increase Amount'}
                                            </label>
                                            <input
                                                type="number"
                                                min="0"
                                                step="0.01"
                                                value={renewalForm.data.annual_increase_value}
                                                onChange={(e) => renewalForm.setData('annual_increase_value', e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500"
                                            />
                                        </div>
                                    </div>

                                    <div className="flex items-center justify-end gap-3 pt-4 border-t">
                                        <button type="button" onClick={() => setShowRenewalForm(false)} className="text-sm text-gray-600 hover:text-gray-900">Cancel</button>
                                        <button
                                            type="submit"
                                            disabled={renewalForm.processing}
                                            className="inline-flex items-center rounded-md bg-emerald-600 px-5 py-2.5 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-50"
                                        >
                                            {renewalForm.processing ? 'Renewing...' : 'Confirm Renewal'}
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    )}

                    {/* Renew Button (when not expired/expiring but admin wants to renew) */}
                    {!showRenewalForm && auth.user.is_admin && (lease.status === 'active' || lease.status === 'expired') && !isExpired() && !isExpiringSoon() && (
                        <div className="flex justify-end">
                            <button
                                onClick={() => setShowRenewalForm(true)}
                                className="inline-flex items-center gap-2 rounded-md bg-emerald-600 px-4 py-2 text-sm font-medium text-white hover:bg-emerald-700"
                            >
                                <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182" /></svg>
                                Renew Lease
                            </button>
                        </div>
                    )}
                </div>
            </div>

            <ConfirmDeleteModal
                show={showTerminate}
                onClose={() => setShowTerminate(false)}
                onConfirm={handleTerminate}
                title="Terminate Lease"
                message="Are you sure you want to terminate this lease? This action cannot be undone. The tenant will be marked as inactive."
                processing={terminating}
            />
        </AuthenticatedLayout>
    );
}
