import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import SearchableSelect from '@/Components/SearchableSelect';
import { Head, Link, useForm } from '@inertiajs/react';

export default function Edit({ lease, shops, tenants }) {
    // Compute move_in_date from start_date and grace_days
    const computedMoveIn = () => {
        if (!lease.start_date) return '';
        const d = new Date(lease.start_date.split('T')[0]);
        d.setDate(d.getDate() - (lease.grace_days || 0));
        return d.toISOString().split('T')[0];
    };

    // Guess lease_duration from start_date and end_date
    const guessedDuration = () => {
        if (!lease.start_date || !lease.end_date) return 'custom';
        const s = new Date(lease.start_date.split('T')[0]);
        const e = new Date(lease.end_date.split('T')[0]);
        const months = (e.getFullYear() - s.getFullYear()) * 12 + (e.getMonth() - s.getMonth());
        if ([6, 11, 12].includes(months)) return String(months);
        return 'custom';
    };

    const { data, setData, post, processing, errors } = useForm({
        _method: 'PUT',
        shop_id: lease.shop_id || '',
        tenant_id: lease.tenant_id || '',
        move_in_date: computedMoveIn(),
        grace_days: lease.grace_days || 0,
        lease_duration: guessedDuration(),
        start_date: lease.start_date ? lease.start_date.split('T')[0] : '',
        end_date: lease.end_date ? lease.end_date.split('T')[0] : '',
        agreed_rent: lease.agreed_rent || '',
        annual_increase_type: lease.annual_increase_type || 'percentage',
        annual_increase_value: lease.annual_increase_value || '10',
        initial_rent: lease.initial_rent || '',
        initial_rent_months: lease.initial_rent_months || '',
        agreed_security_deposit: lease.agreed_security_deposit || '',
        security_deposit_paid: lease.security_deposit_paid || '',
        maintenance_fee: lease.maintenance_fee || '',
        electricity_enabled: lease.electricity_enabled || false,
        electricity_rate_per_unit: lease.electricity_rate_per_unit || '',
        agreement_file: null,
        agreement_notes: lease.agreement_notes || '',
        commission_type: lease.commission_type || 'none',
        commission_amount: lease.commission_amount || '',
        commission_to: lease.commission_to || '',
        commission_phone: lease.commission_phone || '',
        commission_remarks: lease.commission_remarks || '',
    });

    const commissionEnabled = data.commission_type !== 'none';

    // Helper: parse date string safely (avoid timezone shift)
    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}`;
    };

    // Helper: add days to date string
    const addDays = (dateStr, days) => {
        if (!dateStr) return '';
        const d = parseDate(dateStr);
        d.setDate(d.getDate() + parseInt(days || 0));
        return formatYMD(d);
    };

    // Helper: add months to date string
    const addMonths = (dateStr, months) => {
        if (!dateStr || !months) return '';
        const d = parseDate(dateStr);
        d.setMonth(d.getMonth() + parseInt(months));
        d.setDate(d.getDate() - 1);
        return formatYMD(d);
    };

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

    const handleGraceDaysChange = (days) => {
        const grace = parseInt(days) || 0;
        const rentStart = addDays(data.move_in_date, grace);
        const endDate = data.lease_duration !== 'custom' ? addMonths(rentStart, data.lease_duration) : data.end_date;
        setData(prev => ({ ...prev, grace_days: days, start_date: rentStart, end_date: endDate }));
    };

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

    const formatDisplayDate = (dateStr) => {
        if (!dateStr) return '\u2014';
        return new Date(dateStr).toLocaleDateString('en-PK', { day: '2-digit', month: 'short', year: 'numeric' });
    };

    const leaseSummary = () => {
        if (!data.start_date || !data.end_date) return null;
        const start = new Date(data.start_date);
        const end = new Date(data.end_date);
        const diffMs = end - start;
        const totalDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
        const months = Math.floor(totalDays / 30);
        const days = totalDays % 30;
        return { totalDays, months, days };
    };

    const handleCommissionTypeChange = (type) => {
        setData((prev) => {
            const rent = parseFloat(prev.agreed_rent) || 0;
            let amount = '';
            if (type === 'full_rent') amount = rent;
            else if (type === 'half_rent') amount = Math.round(rent / 2);
            else if (type === 'fixed') amount = prev.commission_amount || '';
            return { ...prev, commission_type: type, commission_amount: amount };
        });
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        post(route('leases.update', lease.id), { forceFormData: true });
    };

    const depositRemaining = () => {
        const total = parseFloat(data.agreed_security_deposit) || 0;
        const paid = parseFloat(data.security_deposit_paid) || 0;
        return total - paid;
    };

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

            <div className="py-12">
                <div className="mx-auto max-w-4xl sm:px-6 lg:px-8">
                    <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <form onSubmit={handleSubmit} className="space-y-8">
                                {/* Section 1: Shop & Tenant */}
                                <div>
                                    <h3 className="text-lg font-medium text-gray-900 border-b pb-2 mb-4">Shop & Tenant</h3>
                                    <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Shop <span className="text-red-500">*</span></label>
                                            <SearchableSelect
                                                options={shops.map(shop => ({
                                                    value: shop.id,
                                                    label: `Shop #${shop.shop_number} — ${shop.owner?.name || 'No Owner'}`,
                                                    subtitle: [shop.floor && `Floor: ${shop.floor}`, shop.size && `Size: ${shop.size}`].filter(Boolean).join(' | ') || 'No details',
                                                    icon: shop.shop_number,
                                                }))}
                                                value={data.shop_id}
                                                onChange={(val) => setData('shop_id', val)}
                                                placeholder="Search shop..."
                                                disabled
                                            />
                                            {errors.shop_id && <p className="mt-1 text-sm text-red-600">{errors.shop_id}</p>}
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Tenant <span className="text-red-500">*</span></label>
                                            <SearchableSelect
                                                options={tenants.map(tenant => ({
                                                    value: tenant.id,
                                                    label: tenant.name,
                                                    subtitle: [tenant.phone, tenant.cnic].filter(Boolean).join(' | ') || 'No details',
                                                }))}
                                                value={data.tenant_id}
                                                onChange={(val) => setData('tenant_id', val)}
                                                placeholder="Search tenant..."
                                                disabled
                                            />
                                            {errors.tenant_id && <p className="mt-1 text-sm text-red-600">{errors.tenant_id}</p>}
                                        </div>
                                    </div>
                                </div>

                                {/* Section 2: Lease Period */}
                                <div>
                                    <h3 className="text-lg font-medium text-gray-900 border-b pb-2 mb-4">Lease Period</h3>
                                    {/* Row 1: Move-in & Grace */}
                                    <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Move-in Date <span className="text-red-500">*</span></label>
                                            <input
                                                type="date"
                                                value={data.move_in_date}
                                                onChange={(e) => handleMoveInChange(e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                            />
                                            <p className="mt-1 text-xs text-gray-500">When tenant moves in</p>
                                            {errors.start_date && <p className="mt-1 text-sm text-red-600">{errors.start_date}</p>}
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Grace Days (Free)</label>
                                            <input
                                                type="number"
                                                min="0"
                                                value={data.grace_days}
                                                onChange={(e) => handleGraceDaysChange(e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                            />
                                            <p className="mt-1 text-xs text-gray-500">Free days before rent starts</p>
                                            {errors.grace_days && <p className="mt-1 text-sm text-red-600">{errors.grace_days}</p>}
                                        </div>
                                    </div>
                                    {/* Row 2: Duration & End Date */}
                                    <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 mt-6">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 mb-1">Lease Duration</label>
                                            <div className="flex gap-2">
                                                {[
                                                    { value: '6', label: '6 Months' },
                                                    { value: '11', label: '11 Months' },
                                                    { value: '12', label: '12 Months' },
                                                    { value: 'custom', label: 'Custom' },
                                                ].map((opt) => (
                                                    <button
                                                        key={opt.value}
                                                        type="button"
                                                        onClick={() => handleDurationChange(opt.value)}
                                                        className={`flex-1 rounded-md px-3 py-2.5 text-sm font-medium border-2 transition-all ${
                                                            data.lease_duration === opt.value
                                                                ? 'border-blue-500 bg-blue-50 text-blue-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={data.end_date}
                                                onChange={(e) => setData('end_date', e.target.value)}
                                                readOnly={data.lease_duration !== 'custom'}
                                                className={`mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 ${
                                                    data.lease_duration !== 'custom' ? 'bg-gray-100 cursor-not-allowed' : ''
                                                }`}
                                            />
                                            {data.lease_duration !== 'custom' && (
                                                <p className="mt-1 text-xs text-gray-500">Auto-calculated from duration</p>
                                            )}
                                            {errors.end_date && <p className="mt-1 text-sm text-red-600">{errors.end_date}</p>}
                                        </div>
                                    </div>

                                    {/* Auto-calculated Summary */}
                                    {data.move_in_date && data.start_date && (
                                        <div className="mt-4 rounded-lg border border-blue-200 bg-gradient-to-r from-blue-50 to-indigo-50 p-4">
                                            <div className="flex items-center gap-2 mb-3">
                                                <div className="h-2 w-2 rounded-full bg-blue-500"></div>
                                                <p className="text-xs font-semibold text-blue-800 uppercase tracking-wider">Lease Timeline</p>
                                            </div>
                                            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                                                <div className="rounded-lg bg-white/80 px-3 py-2 border border-blue-100">
                                                    <p className="text-[10px] font-medium text-gray-500 uppercase">Move-in</p>
                                                    <p className="text-sm font-semibold text-gray-900">{formatDisplayDate(data.move_in_date)}</p>
                                                </div>
                                                <div className="rounded-lg bg-white/80 px-3 py-2 border border-blue-100">
                                                    <p className="text-[10px] font-medium text-gray-500 uppercase">Rent Starts</p>
                                                    <p className="text-sm font-semibold text-green-700">{formatDisplayDate(data.start_date)}</p>
                                                    {parseInt(data.grace_days) > 0 && (
                                                        <p className="text-[10px] text-gray-500">{data.grace_days} days free</p>
                                                    )}
                                                </div>
                                                <div className="rounded-lg bg-white/80 px-3 py-2 border border-blue-100">
                                                    <p className="text-[10px] font-medium text-gray-500 uppercase">Lease Ends</p>
                                                    <p className="text-sm font-semibold text-red-600">{data.end_date ? formatDisplayDate(data.end_date) : '\u2014'}</p>
                                                </div>
                                                <div className="rounded-lg bg-white/80 px-3 py-2 border border-blue-100">
                                                    <p className="text-[10px] font-medium text-gray-500 uppercase">Duration</p>
                                                    <p className="text-sm font-semibold text-indigo-700">
                                                        {leaseSummary()
                                                            ? `${leaseSummary().months} months${leaseSummary().days > 0 ? ` ${leaseSummary().days} days` : ''}`
                                                            : '\u2014'
                                                        }
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                </div>

                                {/* Section 3: Rent Agreement */}
                                <div>
                                    <h3 className="text-lg font-medium text-gray-900 border-b pb-2 mb-4">Rent Agreement</h3>
                                    <div className="grid grid-cols-1 gap-6 sm:grid-cols-3">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Regular Monthly Rent (PKR) <span className="text-red-500">*</span></label>
                                            <input
                                                type="number"
                                                min="0"
                                                value={data.agreed_rent}
                                                onChange={(e) => setData('agreed_rent', e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                            />
                                            {errors.agreed_rent && <p className="mt-1 text-sm text-red-600">{errors.agreed_rent}</p>}
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Discounted Initial Rent (PKR)</label>
                                            <input
                                                type="number"
                                                min="0"
                                                value={data.initial_rent}
                                                onChange={(e) => setData('initial_rent', e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                            />
                                            {errors.initial_rent && <p className="mt-1 text-sm text-red-600">{errors.initial_rent}</p>}
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Discount Duration (months)</label>
                                            <input
                                                type="number"
                                                min="0"
                                                value={data.initial_rent_months}
                                                onChange={(e) => setData('initial_rent_months', e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                            />
                                            {errors.initial_rent_months && <p className="mt-1 text-sm text-red-600">{errors.initial_rent_months}</p>}
                                        </div>
                                    </div>
                                    <p className="mt-2 text-xs text-gray-500">If tenant negotiated a lower rent for initial months, enter it here</p>

                                    {/* Annual Rent Increase */}
                                    <div className="mt-6 border-t pt-4">
                                        <h4 className="text-sm font-semibold text-gray-800 mb-3">Annual Rent Increase (on renewal)</h4>
                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700">Increase Type</label>
                                                <div className="mt-2 flex gap-4">
                                                    <label className={`flex-1 flex items-center justify-center gap-2 rounded-lg border-2 px-4 py-3 cursor-pointer transition-all ${
                                                        data.annual_increase_type === 'percentage'
                                                            ? 'border-blue-500 bg-blue-50 text-blue-700'
                                                            : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300'
                                                    }`}>
                                                        <input
                                                            type="radio"
                                                            name="annual_increase_type"
                                                            value="percentage"
                                                            checked={data.annual_increase_type === 'percentage'}
                                                            onChange={(e) => setData('annual_increase_type', e.target.value)}
                                                            className="sr-only"
                                                        />
                                                        <span className="text-lg">%</span>
                                                        <span className="text-sm font-medium">Percentage</span>
                                                    </label>
                                                    <label className={`flex-1 flex items-center justify-center gap-2 rounded-lg border-2 px-4 py-3 cursor-pointer transition-all ${
                                                        data.annual_increase_type === 'fixed'
                                                            ? 'border-blue-500 bg-blue-50 text-blue-700'
                                                            : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300'
                                                    }`}>
                                                        <input
                                                            type="radio"
                                                            name="annual_increase_type"
                                                            value="fixed"
                                                            checked={data.annual_increase_type === 'fixed'}
                                                            onChange={(e) => setData('annual_increase_type', e.target.value)}
                                                            className="sr-only"
                                                        />
                                                        <span className="text-lg">PKR</span>
                                                        <span className="text-sm font-medium">Fixed Amount</span>
                                                    </label>
                                                </div>
                                                {errors.annual_increase_type && <p className="mt-1 text-sm text-red-600">{errors.annual_increase_type}</p>}
                                            </div>
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700">
                                                    {data.annual_increase_type === 'percentage' ? 'Increase Percentage (%)' : 'Increase Amount (PKR)'}
                                                </label>
                                                <input
                                                    type="number"
                                                    min="0"
                                                    step="0.01"
                                                    value={data.annual_increase_value}
                                                    onChange={(e) => setData('annual_increase_value', e.target.value)}
                                                    className="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                                    placeholder={data.annual_increase_type === 'percentage' ? 'e.g. 10' : 'e.g. 5000'}
                                                />
                                                {errors.annual_increase_value && <p className="mt-1 text-sm text-red-600">{errors.annual_increase_value}</p>}
                                            </div>
                                        </div>
                                        {data.agreed_rent && data.annual_increase_value > 0 && (
                                            <div className="mt-3 rounded-lg bg-blue-50 border border-blue-200 px-4 py-3">
                                                <p className="text-xs font-medium text-blue-800">Rent Preview:</p>
                                                <div className="mt-1 flex gap-4 text-xs text-blue-700">
                                                    <span>Year 1: PKR {parseFloat(data.agreed_rent).toLocaleString()}</span>
                                                    <span>Year 2: PKR {
                                                        data.annual_increase_type === 'percentage'
                                                            ? Math.round(parseFloat(data.agreed_rent) * (1 + parseFloat(data.annual_increase_value) / 100)).toLocaleString()
                                                            : (parseFloat(data.agreed_rent) + parseFloat(data.annual_increase_value)).toLocaleString()
                                                    }</span>
                                                    <span>Year 3: PKR {
                                                        data.annual_increase_type === 'percentage'
                                                            ? Math.round(parseFloat(data.agreed_rent) * Math.pow(1 + parseFloat(data.annual_increase_value) / 100, 2)).toLocaleString()
                                                            : (parseFloat(data.agreed_rent) + 2 * parseFloat(data.annual_increase_value)).toLocaleString()
                                                    }</span>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Section 4: Security Deposit */}
                                <div>
                                    <h3 className="text-lg font-medium text-gray-900 border-b pb-2 mb-4">Security Deposit</h3>
                                    <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Total Security Deposit (PKR)</label>
                                            <input
                                                type="number"
                                                min="0"
                                                value={data.agreed_security_deposit}
                                                onChange={(e) => setData('agreed_security_deposit', e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                            />
                                            {errors.agreed_security_deposit && <p className="mt-1 text-sm text-red-600">{errors.agreed_security_deposit}</p>}
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Amount Paid Now (PKR)</label>
                                            <input
                                                type="number"
                                                min="0"
                                                value={data.security_deposit_paid}
                                                onChange={(e) => setData('security_deposit_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"
                                            />
                                            {errors.security_deposit_paid && <p className="mt-1 text-sm text-red-600">{errors.security_deposit_paid}</p>}
                                        </div>
                                    </div>
                                    {(data.agreed_security_deposit || data.security_deposit_paid) && (
                                        <p className={`mt-2 text-sm font-medium ${depositRemaining() > 0 ? 'text-red-600' : 'text-green-600'}`}>
                                            Remaining: PKR {depositRemaining().toLocaleString()}
                                        </p>
                                    )}
                                </div>

                                {/* Section 5: Optional Charges */}
                                <div>
                                    <h3 className="text-lg font-medium text-gray-900 border-b pb-2 mb-4">Optional Charges</h3>
                                    <div className="space-y-4">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Maintenance Fee (PKR)</label>
                                            <input
                                                type="number"
                                                min="0"
                                                value={data.maintenance_fee}
                                                onChange={(e) => setData('maintenance_fee', e.target.value)}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:max-w-xs"
                                            />
                                            {errors.maintenance_fee && <p className="mt-1 text-sm text-red-600">{errors.maintenance_fee}</p>}
                                        </div>
                                        <div className="flex items-center gap-3">
                                            <input
                                                type="checkbox"
                                                id="electricity_enabled"
                                                checked={data.electricity_enabled}
                                                onChange={(e) => setData('electricity_enabled', e.target.checked)}
                                                className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                                            />
                                            <label htmlFor="electricity_enabled" className="text-sm font-medium text-gray-700">Enable Electricity Meter Tracking</label>
                                        </div>
                                        {data.electricity_enabled && (
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700">Electricity Rate Per Unit (PKR)</label>
                                                <input
                                                    type="number"
                                                    min="0"
                                                    step="0.01"
                                                    value={data.electricity_rate_per_unit}
                                                    onChange={(e) => setData('electricity_rate_per_unit', e.target.value)}
                                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:max-w-xs"
                                                />
                                                {errors.electricity_rate_per_unit && <p className="mt-1 text-sm text-red-600">{errors.electricity_rate_per_unit}</p>}
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Section 6: Agreement */}
                                <div>
                                    <h3 className="text-lg font-medium text-gray-900 border-b pb-2 mb-4">Agreement</h3>
                                    <div className="space-y-4">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Agreement File (PDF)</label>
                                            {lease.agreement_file && (
                                                <p className="mb-1 text-xs text-gray-500">
                                                    Current file: <a href={`/storage/${lease.agreement_file}`} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">View</a>
                                                </p>
                                            )}
                                            <input
                                                type="file"
                                                accept=".pdf"
                                                onChange={(e) => setData('agreement_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"
                                            />
                                            {errors.agreement_file && <p className="mt-1 text-sm text-red-600">{errors.agreement_file}</p>}
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700">Agreement Notes</label>
                                            <textarea
                                                value={data.agreement_notes}
                                                onChange={(e) => setData('agreement_notes', e.target.value)}
                                                rows={4}
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                            />
                                            {errors.agreement_notes && <p className="mt-1 text-sm text-red-600">{errors.agreement_notes}</p>}
                                        </div>
                                    </div>
                                </div>

                                {/* Section 7: Referral Commission */}
                                <div>
                                    <h3 className="text-lg font-medium text-gray-900 border-b pb-2 mb-4">Referral Commission</h3>
                                    <div className="flex items-center gap-3 mb-4">
                                        <input
                                            type="checkbox"
                                            id="commission_enabled"
                                            checked={commissionEnabled}
                                            onChange={(e) => {
                                                if (!e.target.checked) {
                                                    setData((prev) => ({ ...prev, commission_type: 'none', commission_amount: '', commission_to: '', commission_phone: '', commission_remarks: '' }));
                                                } else {
                                                    handleCommissionTypeChange('full_rent');
                                                }
                                            }}
                                            className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                                        />
                                        <label htmlFor="commission_enabled" className="text-sm font-medium text-gray-700">Someone referred this tenant (pay commission)</label>
                                    </div>

                                    {commissionEnabled && (
                                        <div className="space-y-4 rounded-lg border border-gray-200 bg-gray-50 p-4">
                                            {lease.commission_paid && (
                                                <div className="rounded-lg bg-green-50 border border-green-200 px-4 py-3">
                                                    <p className="text-sm font-medium text-green-800">This commission has already been paid. Changes here won't affect the payment record.</p>
                                                </div>
                                            )}
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700 mb-2">Commission Type</label>
                                                <div className="flex gap-3">
                                                    {[
                                                        { value: 'full_rent', label: 'Full Rent', icon: '100%' },
                                                        { value: 'half_rent', label: 'Half Rent', icon: '50%' },
                                                        { value: 'fixed', label: 'Custom Amount', icon: 'PKR' },
                                                    ].map((opt) => (
                                                        <label
                                                            key={opt.value}
                                                            className={`flex-1 flex flex-col items-center justify-center gap-1 rounded-lg border-2 px-3 py-3 cursor-pointer transition-all ${
                                                                data.commission_type === opt.value
                                                                    ? 'border-blue-500 bg-blue-50 text-blue-700'
                                                                    : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300'
                                                            }`}
                                                        >
                                                            <input
                                                                type="radio"
                                                                name="commission_type"
                                                                value={opt.value}
                                                                checked={data.commission_type === opt.value}
                                                                onChange={() => handleCommissionTypeChange(opt.value)}
                                                                className="sr-only"
                                                            />
                                                            <span className="text-lg font-bold">{opt.icon}</span>
                                                            <span className="text-xs font-medium">{opt.label}</span>
                                                        </label>
                                                    ))}
                                                </div>
                                                {errors.commission_type && <p className="mt-1 text-sm text-red-600">{errors.commission_type}</p>}
                                            </div>

                                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                                <div>
                                                    <label className="block text-sm font-medium text-gray-700">Commission Amount (PKR)</label>
                                                    <input
                                                        type="number"
                                                        min="0"
                                                        value={data.commission_amount}
                                                        onChange={(e) => setData('commission_amount', e.target.value)}
                                                        readOnly={data.commission_type !== 'fixed'}
                                                        className={`mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 ${
                                                            data.commission_type !== 'fixed' ? 'bg-gray-100' : ''
                                                        }`}
                                                    />
                                                    {data.commission_type !== 'fixed' && (
                                                        <p className="mt-1 text-xs text-gray-500">Auto-calculated from rent</p>
                                                    )}
                                                    {errors.commission_amount && <p className="mt-1 text-sm text-red-600">{errors.commission_amount}</p>}
                                                </div>
                                                <div>
                                                    <label className="block text-sm font-medium text-gray-700">Receiver Name <span className="text-red-500">*</span></label>
                                                    <input
                                                        type="text"
                                                        value={data.commission_to}
                                                        onChange={(e) => setData('commission_to', e.target.value)}
                                                        placeholder="Who gets the commission?"
                                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                                    />
                                                    {errors.commission_to && <p className="mt-1 text-sm text-red-600">{errors.commission_to}</p>}
                                                </div>
                                                <div>
                                                    <label className="block text-sm font-medium text-gray-700">Receiver Phone</label>
                                                    <input
                                                        type="text"
                                                        value={data.commission_phone}
                                                        onChange={(e) => setData('commission_phone', e.target.value)}
                                                        placeholder="Phone number"
                                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                                    />
                                                    {errors.commission_phone && <p className="mt-1 text-sm text-red-600">{errors.commission_phone}</p>}
                                                </div>
                                            </div>

                                            <div>
                                                <label className="block text-sm font-medium text-gray-700">Remarks</label>
                                                <textarea
                                                    value={data.commission_remarks}
                                                    onChange={(e) => setData('commission_remarks', e.target.value)}
                                                    rows={2}
                                                    placeholder="Any notes about this commission..."
                                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                                />
                                                {errors.commission_remarks && <p className="mt-1 text-sm text-red-600">{errors.commission_remarks}</p>}
                                            </div>
                                        </div>
                                    )}
                                </div>

                                {/* Actions */}
                                <div className="flex items-center justify-end gap-4 border-t pt-4">
                                    <Link href={route('leases.index')} className="text-sm text-gray-600 hover:text-gray-900">Cancel</Link>
                                    <button
                                        type="submit"
                                        disabled={processing}
                                        className="inline-flex items-center rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
                                    >
                                        Update Lease
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
