import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, router, useForm } from '@inertiajs/react';
import { useState, useMemo } from 'react';

const FACILITY_LABELS = {
    all:                  'جميع المرافق',
    pool:                 'حمام السباحة',
    chalet:               'الشاليهات',
    hall:                 'القاعات',
    conference_building:  'بيت المؤتمرات',
    sports_court:         'الملاعب',
    entry:                'تذاكر الدخول',
};

const FACILITY_COLORS = {
    all:                 'bg-gray-100 text-gray-700',
    pool:                'bg-sky-100 text-sky-700',
    chalet:              'bg-teal-100 text-teal-700',
    hall:                'bg-indigo-100 text-indigo-700',
    conference_building: 'bg-purple-100 text-purple-700',
    sports_court:        'bg-green-100 text-green-700',
    entry:               'bg-orange-100 text-orange-700',
};

const INPUT = 'w-full rounded-lg border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500';

const DAY_NAMES_AR = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];

function lockScopeLabel(lock) {
    switch (lock.facility_type) {
        case 'conference_building':
            if (lock.conference_room_id)     return `غرفة ${lock.room_number     ?? lock.conference_room_id}`;
            if (lock.conference_building_id) return `مبنى ${lock.building_name   ?? lock.conference_building_id}`;
            return 'المركز كله';
        case 'chalet':
            if (lock.chalet_id)       return `شاليه ${lock.chalet_number ?? lock.chalet_id}`;
            if (lock.chalet_level_id) return `مستوى: ${lock.level_label  ?? lock.chalet_level_id}`;
            return null;
        case 'hall':
            if (lock.hall_id) return lock.hall_name ?? `قاعة #${lock.hall_id}`;
            return null;
        case 'sports_court':
            if (lock.sports_court_id) return lock.court_name ?? `ملعب #${lock.sports_court_id}`;
            return null;
        default:
            return null;
    }
}

function ScopePanel({ color, children }) {
    const themes = {
        purple: 'bg-purple-50 border-purple-100',
        teal:   'bg-teal-50   border-teal-100',
        indigo: 'bg-indigo-50 border-indigo-100',
        green:  'bg-green-50  border-green-100',
    };
    return (
        <div className={`rounded-lg border p-4 space-y-3 ${themes[color] ?? themes.purple}`}>
            {children}
        </div>
    );
}

function ScopeButtons({ options, value, onChange, color }) {
    const active = {
        purple: 'border-purple-500 bg-purple-100 text-purple-800',
        teal:   'border-teal-500   bg-teal-100   text-teal-800',
        indigo: 'border-indigo-500 bg-indigo-100 text-indigo-800',
        green:  'border-green-500  bg-green-100  text-green-800',
    };
    const hover = {
        purple: 'hover:border-purple-300',
        teal:   'hover:border-teal-300',
        indigo: 'hover:border-indigo-300',
        green:  'hover:border-green-300',
    };
    return (
        <div className="flex gap-2 flex-wrap">
            {options.map(opt => (
                <button key={opt.value} type="button" onClick={() => onChange(opt.value)}
                    className={`px-3 py-1.5 rounded-lg border-2 text-xs font-semibold transition-all ${
                        value === opt.value
                            ? (active[color] ?? active.purple)
                            : `border-gray-200 text-gray-600 ${hover[color] ?? hover.purple}`
                    }`}>
                    {opt.label}
                </button>
            ))}
        </div>
    );
}

export default function BookingLocksIndex({
    locks,
    conferenceBuildings = [],
    chaletLevels        = [],
    unleveledChalets    = [],
    halls               = [],
    courts              = [],
    poolOperatingDays   = [],
    hallOperatingDays   = {},
    courtOperatingDays  = {},
}) {
    const [showAdd,  setShowAdd]  = useState(false);
    const [deleteId, setDeleteId] = useState(null);

    // Per-facility scope state
    const [confScope,   setConfScope]   = useState('center'); // center | building | room
    const [chaletScope, setChaletScope] = useState('all');    // all | level | chalet
    const [hallScope,   setHallScope]   = useState('all');    // all | hall
    const [courtScope,  setCourtScope]  = useState('all');    // all | court

    const { data, setData, post, processing, errors, reset, clearErrors } = useForm({
        facility_type:           'all',
        // conference
        conference_building_id:  '',
        conference_room_id:      '',
        // chalet
        chalet_level_id:         '',
        chalet_id:               '',
        // hall
        hall_id:                 '',
        // sports court
        sports_court_id:         '',
        // common
        date_from:               '',
        date_to:                 '',
        reason:                  '',
    });

    // Conference: rooms for selected building
    const selectedBuilding = useMemo(
        () => conferenceBuildings.find(b => String(b.id) === String(data.conference_building_id)),
        [conferenceBuildings, data.conference_building_id]
    );

    // Chalet: chalets for selected level
    const selectedLevelChalets = useMemo(() => {
        if (!data.chalet_level_id) return unleveledChalets;
        return chaletLevels.find(l => String(l.id) === String(data.chalet_level_id))?.chalets ?? [];
    }, [chaletLevels, unleveledChalets, data.chalet_level_id]);

    // Compute the set of valid JS day-of-week values (0=Sun…6=Sat) for the current selection.
    // Returns null when there is no restriction (all days allowed).
    const validDays = useMemo(() => {
        const ft = data.facility_type;
        let rawDays = null;

        if (ft === 'pool' || ft === 'entry') {
            rawDays = poolOperatingDays;
        } else if (ft === 'hall') {
            if (hallScope === 'hall' && data.hall_id) {
                rawDays = hallOperatingDays[String(data.hall_id)] ?? [];
            } else {
                rawDays = Object.values(hallOperatingDays).flat();
            }
        } else if (ft === 'sports_court') {
            if (courtScope === 'court' && data.sports_court_id) {
                rawDays = courtOperatingDays[String(data.sports_court_id)] ?? [];
            } else {
                rawDays = Object.values(courtOperatingDays).flat();
            }
        }

        if (!rawDays || rawDays.length === 0) return null;
        if (rawDays.includes(7)) return null; // 7 = every day
        return new Set(rawDays);
    }, [data.facility_type, data.hall_id, data.sports_court_id, hallScope, courtScope,
        poolOperatingDays, hallOperatingDays, courtOperatingDays]);

    function checkDayValid(dateStr) {
        if (!validDays || !dateStr) return '';
        const dow = new Date(dateStr + 'T12:00:00').getDay();
        if (validDays.has(dow)) return '';
        return `هذا اليوم غير متاح. الأيام المتاحة: ${[...validDays].sort().map(d => DAY_NAMES_AR[d]).join('، ')}`;
    }

    const dateFromError = useMemo(() => checkDayValid(data.date_from), [validDays, data.date_from]);
    const dateToError   = useMemo(() => checkDayValid(data.date_to),   [validDays, data.date_to]);

    function handleFacilityChange(val) {
        setData(d => ({
            ...d,
            facility_type: val,
            conference_building_id: '', conference_room_id: '',
            chalet_level_id: '', chalet_id: '',
            hall_id: '',
            sports_court_id: '',
        }));
        setConfScope('center');
        setChaletScope('all');
        setHallScope('all');
        setCourtScope('all');
        clearErrors();
    }

    function handleConfScopeChange(scope) {
        setConfScope(scope);
        setData(d => ({ ...d, conference_building_id: '', conference_room_id: '' }));
    }

    function handleChaletScopeChange(scope) {
        setChaletScope(scope);
        setData(d => ({ ...d, chalet_level_id: '', chalet_id: '' }));
    }

    function handleHallScopeChange(scope) {
        setHallScope(scope);
        setData(d => ({ ...d, hall_id: '' }));
    }

    function handleCourtScopeChange(scope) {
        setCourtScope(scope);
        setData(d => ({ ...d, sports_court_id: '' }));
    }

    function submitAdd(e) {
        e.preventDefault();
        if (dateFromError || dateToError) return;
        const payload = {
            facility_type: data.facility_type,
            date_from:     data.date_from,
            date_to:       data.date_to,
            reason:        data.reason,
        };

        if (data.facility_type === 'conference_building') {
            if (confScope === 'building' || confScope === 'room') {
                payload.conference_building_id = data.conference_building_id || null;
            }
            if (confScope === 'room') {
                payload.conference_room_id = data.conference_room_id || null;
            }
        }

        if (data.facility_type === 'chalet') {
            if (chaletScope === 'level' || chaletScope === 'chalet') {
                payload.chalet_level_id = data.chalet_level_id || null;
            }
            if (chaletScope === 'chalet') {
                payload.chalet_id = data.chalet_id || null;
            }
        }

        if (data.facility_type === 'hall' && hallScope === 'hall') {
            payload.hall_id = data.hall_id || null;
        }

        if (data.facility_type === 'sports_court' && courtScope === 'court') {
            payload.sports_court_id = data.sports_court_id || null;
        }

        post(route('booking-locks.store'), {
            data: payload,
            preserveScroll: true,
            onSuccess: () => {
                reset();
                setShowAdd(false);
                setConfScope('center');
                setChaletScope('all');
                setHallScope('all');
                setCourtScope('all');
            },
        });
    }

    function doDelete() {
        router.delete(route('booking-locks.destroy', deleteId), {
            preserveScroll: true,
            onFinish: () => setDeleteId(null),
        });
    }

    const today    = new Date().toISOString().slice(0, 10);
    const upcoming = locks.filter(l => l.date_to >= today);
    const past     = locks.filter(l => l.date_to <  today);

    return (
        <AuthenticatedLayout
            header={
                <div className="flex items-center justify-between">
                    <h1 className="text-xl font-bold text-gray-800">إغلاق الحجوزات</h1>
                    <button onClick={() => setShowAdd(v => !v)}
                        className="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 transition-colors">
                        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                        </svg>
                        إضافة فترة إغلاق
                    </button>
                </div>
            }
        >
            <Head title="إغلاق الحجوزات" />

            {/* Confirm Delete Dialog */}
            {deleteId && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-sm p-6">
                        <p className="text-sm font-medium text-gray-800 mb-4">هل تريد حذف فترة الإغلاق؟</p>
                        <div className="flex justify-end gap-3">
                            <button onClick={() => setDeleteId(null)}
                                className="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                                إلغاء
                            </button>
                            <button onClick={doDelete}
                                className="rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700">
                                حذف
                            </button>
                        </div>
                    </div>
                </div>
            )}

            <div className="p-6 space-y-6">
                {/* Add Form */}
                {showAdd && (
                    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
                        <h2 className="text-sm font-semibold text-gray-800 mb-4">إضافة فترة إغلاق جديدة</h2>
                        <form onSubmit={submitAdd} className="space-y-4" noValidate>
                            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                                {/* Facility */}
                                <div>
                                    <label className="block text-xs font-medium text-gray-600 mb-1">
                                        المرفق <span className="text-red-500">*</span>
                                    </label>
                                    <select value={data.facility_type}
                                        onChange={e => handleFacilityChange(e.target.value)}
                                        className={INPUT}>
                                        {Object.entries(FACILITY_LABELS).map(([k, v]) => (
                                            <option key={k} value={k}>{v}</option>
                                        ))}
                                    </select>
                                    {errors.facility_type && <p className="mt-1 text-xs text-red-600">{errors.facility_type}</p>}
                                </div>

                                {/* Date From */}
                                <div>
                                    <label className="block text-xs font-medium text-gray-600 mb-1">
                                        من تاريخ <span className="text-red-500">*</span>
                                    </label>
                                    <input type="date" value={data.date_from}
                                        onChange={e => { setData('date_from', e.target.value); clearErrors('date_from'); }}
                                        min={today}
                                        className={`${INPUT} ${dateFromError ? 'border-red-400' : ''}`} />
                                    {validDays && !dateFromError && (
                                        <p className="mt-1 text-xs text-gray-400">الأيام المتاحة: {[...validDays].sort().map(d => DAY_NAMES_AR[d]).join('، ')}</p>
                                    )}
                                    {dateFromError && <p className="mt-1 text-xs text-red-600">{dateFromError}</p>}
                                    {errors.date_from && <p className="mt-1 text-xs text-red-600">{errors.date_from}</p>}
                                </div>

                                {/* Date To */}
                                <div>
                                    <label className="block text-xs font-medium text-gray-600 mb-1">
                                        إلى تاريخ <span className="text-red-500">*</span>
                                    </label>
                                    <input type="date" value={data.date_to}
                                        onChange={e => { setData('date_to', e.target.value); clearErrors('date_to'); }}
                                        min={data.date_from || today}
                                        disabled={!data.date_from}
                                        className={`${INPUT} ${dateToError ? 'border-red-400' : ''} ${!data.date_from ? 'opacity-50 cursor-not-allowed' : ''}`} />
                                    {validDays && !dateToError && (
                                        <p className="mt-1 text-xs text-gray-400">الأيام المتاحة: {[...validDays].sort().map(d => DAY_NAMES_AR[d]).join('، ')}</p>
                                    )}
                                    {dateToError && <p className="mt-1 text-xs text-red-600">{dateToError}</p>}
                                    {errors.date_to && <p className="mt-1 text-xs text-red-600">{errors.date_to}</p>}
                                </div>

                                {/* Reason */}
                                <div>
                                    <label className="block text-xs font-medium text-gray-600 mb-1">السبب (اختياري)</label>
                                    <input type="text" value={data.reason}
                                        onChange={e => { setData('reason', e.target.value); clearErrors('reason'); }}
                                        className={INPUT} placeholder="مثال: صيانة، إجازة رسمية…" />
                                    {errors.reason && <p className="mt-1 text-xs text-red-600">{errors.reason}</p>}
                                </div>
                            </div>

                            {/* ── Conference scope ── */}
                            {data.facility_type === 'conference_building' && (
                                <ScopePanel color="purple">
                                    <p className="text-xs font-semibold text-purple-700">نطاق الإغلاق</p>
                                    <ScopeButtons color="purple" value={confScope} onChange={handleConfScopeChange}
                                        options={[
                                            { value: 'center',   label: 'المركز كله' },
                                            { value: 'building', label: 'مبنى معين' },
                                            { value: 'room',     label: 'غرفة معينة' },
                                        ]} />

                                    {(confScope === 'building' || confScope === 'room') && (
                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                            <div>
                                                <label className="block text-xs font-medium text-gray-600 mb-1">
                                                    المبنى <span className="text-red-500">*</span>
                                                </label>
                                                <select value={data.conference_building_id}
                                                    onChange={e => { setData(d => ({ ...d, conference_building_id: e.target.value, conference_room_id: '' })); clearErrors('conference_building_id'); }}
                                                    className={INPUT}>
                                                    <option value="">— اختر مبنى —</option>
                                                    {conferenceBuildings.map(b => (
                                                        <option key={b.id} value={b.id}>
                                                            {b.name}{b.letter ? ` (${b.letter})` : ''}
                                                        </option>
                                                    ))}
                                                </select>
                                                {errors.conference_building_id && <p className="mt-1 text-xs text-red-600">{errors.conference_building_id}</p>}
                                            </div>

                                            {confScope === 'room' && selectedBuilding && (
                                                <div>
                                                    <label className="block text-xs font-medium text-gray-600 mb-1">
                                                        الغرفة <span className="text-red-500">*</span>
                                                    </label>
                                                    <select value={data.conference_room_id}
                                                        onChange={e => { setData('conference_room_id', e.target.value); clearErrors('conference_room_id'); }}
                                                        className={INPUT}>
                                                        <option value="">— اختر غرفة —</option>
                                                        {(selectedBuilding.rooms ?? []).map(r => (
                                                            <option key={r.id} value={r.id}>غرفة {r.room_number}</option>
                                                        ))}
                                                    </select>
                                                    {errors.conference_room_id && <p className="mt-1 text-xs text-red-600">{errors.conference_room_id}</p>}
                                                </div>
                                            )}
                                        </div>
                                    )}
                                </ScopePanel>
                            )}

                            {/* ── Chalet scope ── */}
                            {data.facility_type === 'chalet' && (
                                <ScopePanel color="teal">
                                    <p className="text-xs font-semibold text-teal-700">نطاق الإغلاق</p>
                                    <ScopeButtons color="teal" value={chaletScope} onChange={handleChaletScopeChange}
                                        options={[
                                            { value: 'all',    label: 'كل الشاليهات' },
                                            { value: 'level',  label: 'دور معين' },
                                            { value: 'chalet', label: 'شاليه معين' },
                                        ]} />

                                    {(chaletScope === 'level' || chaletScope === 'chalet') && (
                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                            <div>
                                                <label className="block text-xs font-medium text-gray-600 mb-1">
                                                    الدور <span className="text-red-500">*</span>
                                                </label>
                                                <select value={data.chalet_level_id}
                                                    onChange={e => { setData(d => ({ ...d, chalet_level_id: e.target.value, chalet_id: '' })); clearErrors('chalet_level_id'); }}
                                                    className={INPUT}>
                                                    <option value="">— اختر دور —</option>
                                                    {chaletLevels.map(l => (
                                                        <option key={l.id} value={l.id}>{l.label}</option>
                                                    ))}
                                                </select>
                                                {errors.chalet_level_id && <p className="mt-1 text-xs text-red-600">{errors.chalet_level_id}</p>}
                                            </div>

                                            {chaletScope === 'chalet' && (
                                                <div>
                                                    <label className="block text-xs font-medium text-gray-600 mb-1">
                                                        الشاليه <span className="text-red-500">*</span>
                                                    </label>
                                                    <select value={data.chalet_id}
                                                        onChange={e => { setData('chalet_id', e.target.value); clearErrors('chalet_id'); }}
                                                        className={INPUT}>
                                                        <option value="">— اختر شاليه —</option>
                                                        {selectedLevelChalets.map(c => (
                                                            <option key={c.id} value={c.id}>شاليه {c.chalet_number}</option>
                                                        ))}
                                                    </select>
                                                    {errors.chalet_id && <p className="mt-1 text-xs text-red-600">{errors.chalet_id}</p>}
                                                </div>
                                            )}
                                        </div>
                                    )}
                                </ScopePanel>
                            )}

                            {/* ── Hall scope ── */}
                            {data.facility_type === 'hall' && halls.length > 0 && (
                                <ScopePanel color="indigo">
                                    <p className="text-xs font-semibold text-indigo-700">نطاق الإغلاق</p>
                                    <ScopeButtons color="indigo" value={hallScope} onChange={handleHallScopeChange}
                                        options={[
                                            { value: 'all',  label: 'كل القاعات' },
                                            { value: 'hall', label: 'قاعة معينة' },
                                        ]} />

                                    {hallScope === 'hall' && (
                                        <div className="max-w-xs">
                                            <label className="block text-xs font-medium text-gray-600 mb-1">
                                                القاعة <span className="text-red-500">*</span>
                                            </label>
                                            <select value={data.hall_id}
                                                onChange={e => { setData('hall_id', e.target.value); clearErrors('hall_id'); }}
                                                className={INPUT}>
                                                <option value="">— اختر قاعة —</option>
                                                {halls.map(h => (
                                                    <option key={h.id} value={h.id}>{h.name}</option>
                                                ))}
                                            </select>
                                            {errors.hall_id && <p className="mt-1 text-xs text-red-600">{errors.hall_id}</p>}
                                        </div>
                                    )}
                                </ScopePanel>
                            )}

                            {/* ── Sports court scope ── */}
                            {data.facility_type === 'sports_court' && courts.length > 0 && (
                                <ScopePanel color="green">
                                    <p className="text-xs font-semibold text-green-700">نطاق الإغلاق</p>
                                    <ScopeButtons color="green" value={courtScope} onChange={handleCourtScopeChange}
                                        options={[
                                            { value: 'all',   label: 'كل الملاعب' },
                                            { value: 'court', label: 'ملعب معين' },
                                        ]} />

                                    {courtScope === 'court' && (
                                        <div className="max-w-xs">
                                            <label className="block text-xs font-medium text-gray-600 mb-1">
                                                الملعب <span className="text-red-500">*</span>
                                            </label>
                                            <select value={data.sports_court_id}
                                                onChange={e => { setData('sports_court_id', e.target.value); clearErrors('sports_court_id'); }}
                                                className={INPUT}>
                                                <option value="">— اختر ملعب —</option>
                                                {courts.map(c => (
                                                    <option key={c.id} value={c.id}>{c.name}</option>
                                                ))}
                                            </select>
                                            {errors.sports_court_id && <p className="mt-1 text-xs text-red-600">{errors.sports_court_id}</p>}
                                        </div>
                                    )}
                                </ScopePanel>
                            )}

                            <div className="flex justify-end gap-3 pt-2 border-t border-gray-100">
                                <button type="button"
                                    onClick={() => {
                                        setShowAdd(false);
                                        setConfScope('center');
                                        setChaletScope('all');
                                        setHallScope('all');
                                        setCourtScope('all');
                                    }}
                                    className="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors">
                                    إلغاء
                                </button>
                                <button type="submit" disabled={processing}
                                    className="rounded-lg bg-indigo-600 px-5 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50 transition-colors">
                                    {processing ? 'جارٍ الحفظ…' : 'حفظ'}
                                </button>
                            </div>
                        </form>
                    </div>
                )}

                {/* Upcoming / Active Locks */}
                <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                    <div className="px-5 py-4 border-b border-gray-100 bg-gray-50">
                        <h2 className="text-sm font-semibold text-gray-800">
                            فترات الإغلاق الحالية والقادمة
                            {upcoming.length > 0 && (
                                <span className="mr-2 rounded-full bg-amber-100 px-2 py-0.5 text-xs text-amber-700">
                                    {upcoming.length}
                                </span>
                            )}
                        </h2>
                    </div>
                    {upcoming.length === 0 ? (
                        <div className="p-8 text-center text-sm text-gray-400">لا توجد فترات إغلاق نشطة أو قادمة.</div>
                    ) : (
                        <LockTable locks={upcoming} onDelete={id => setDeleteId(id)} />
                    )}
                </div>

                {/* Past Locks */}
                {past.length > 0 && (
                    <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                        <div className="px-5 py-4 border-b border-gray-100 bg-gray-50">
                            <h2 className="text-sm font-semibold text-gray-500">فترات إغلاق منتهية</h2>
                        </div>
                        <LockTable locks={past} onDelete={id => setDeleteId(id)} past />
                    </div>
                )}
            </div>
        </AuthenticatedLayout>
    );
}

function LockTable({ locks, onDelete, past = false }) {
    return (
        <div className="overflow-x-auto">
            <table className="min-w-full text-sm">
                <thead className="bg-gray-50 text-gray-500 text-xs border-b border-gray-100">
                    <tr>
                        <th className="px-4 py-3 text-right font-medium">المرفق</th>
                        <th className="px-4 py-3 text-right font-medium">النطاق</th>
                        <th className="px-4 py-3 text-right font-medium">من</th>
                        <th className="px-4 py-3 text-right font-medium">إلى</th>
                        <th className="px-4 py-3 text-right font-medium">السبب</th>
                        {!past && <th className="px-4 py-3"></th>}
                    </tr>
                </thead>
                <tbody className="divide-y divide-gray-50">
                    {locks.map(l => {
                        const scope = lockScopeLabel(l);
                        return (
                            <tr key={l.id} className={`transition-colors ${past ? 'opacity-60' : 'hover:bg-gray-50'}`}>
                                <td className="px-4 py-3">
                                    <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${FACILITY_COLORS[l.facility_type] ?? 'bg-gray-100 text-gray-700'}`}>
                                        {FACILITY_LABELS[l.facility_type] ?? l.facility_type}
                                    </span>
                                </td>
                                <td className="px-4 py-3 text-gray-600 text-xs">
                                    {scope ?? <span className="text-gray-300">—</span>}
                                </td>
                                <td className="px-4 py-3 text-gray-700 whitespace-nowrap">{l.date_from}</td>
                                <td className="px-4 py-3 text-gray-700 whitespace-nowrap">{l.date_to}</td>
                                <td className="px-4 py-3 text-gray-500 max-w-xs">
                                    {l.reason || <span className="text-gray-300">—</span>}
                                </td>
                                {!past && (
                                    <td className="px-4 py-3 text-left">
                                        <button onClick={() => onDelete(l.id)}
                                            className="text-red-400 hover:text-red-600 text-xs font-medium transition-colors">
                                            حذف
                                        </button>
                                    </td>
                                )}
                            </tr>
                        );
                    })}
                </tbody>
            </table>
        </div>
    );
}
