@props([
    'spaces',
    'booking' => null,
    'spaceId' => null,
    'eventStart' => null,
    'eventEnd' => null,
    'setupStart' => null,
    'breakdownEnd' => null,
    'disabled' => false,
])

@php
    $bookingSpace = $booking?->spaces?->first();
    $selectedSpaceId = old('space_id', $spaceId ?? $bookingSpace?->space_id);
    $selectedEventStart = old('event_start', $eventStart ?? $bookingSpace?->event_start?->format('Y-m-d\TH:i') ?? $booking?->event_start?->format('Y-m-d\TH:i'));
    $selectedEventEnd = old('event_end', $eventEnd ?? $bookingSpace?->event_end?->format('Y-m-d\TH:i') ?? $booking?->event_end?->format('Y-m-d\TH:i'));
    $selectedSetupStart = old('setup_start', $setupStart ?? $bookingSpace?->setup_start?->format('Y-m-d\TH:i'));
    $selectedBreakdownEnd = old('breakdown_end', $breakdownEnd ?? $bookingSpace?->breakdown_end?->format('Y-m-d\TH:i'));
    $spaceMeta = $spaces->mapWithKeys(fn ($s) => [$s->id => [
        'setup' => (int) ($s->setup_duration_minutes ?? 0),
        'breakdown' => (int) ($s->breakdown_duration_minutes ?? 0),
    ]]);
@endphp

<div
    class="mb-4"
    x-data="spaceDatePicker(@js([
        'spaceId' => (string) ($selectedSpaceId ?? ''),
        'eventStart' => $selectedEventStart,
        'eventEnd' => $selectedEventEnd,
        'setupStart' => $selectedSetupStart,
        'breakdownEnd' => $selectedBreakdownEnd,
        'statusLabel' => 'Select space and dates',
        'statusClass' => 'text-muted',
        'disabled' => (bool) $disabled || (bool) $booking,
        'busyDates' => [],
    ]), @js($spaceMeta), @js(route('availability.busy-dates')), @js(route('availability.check')))"
    x-init="init()"
>
    <h5 class="mb-3">Space &amp; Event Dates</h5>

    @if ($booking)
        <input type="hidden" name="booking_id" value="{{ $booking->id }}">
        <div class="alert alert-info py-2 mb-3">
            Linked to booking <strong>{{ $booking->booking_number }}</strong>. Space selection is read-only.
        </div>
    @endif

    <div class="row g-3">
        <div class="col-md-6">
            <label class="form-label" for="space_id">Space</label>
            <select name="space_id" id="space_id" class="form-select" x-model="spaceId" @change="onSpaceChange()" @if ($disabled || $booking) disabled @endif>
                <option value="">Select space</option>
                @foreach ($spaces as $space)
                    <option value="{{ $space->id }}" @selected((string) $selectedSpaceId === (string) $space->id)>
                        {{ $space->name }} ({{ $space->code }})
                    </option>
                @endforeach
            </select>
            @if (($disabled || $booking) && $selectedSpaceId)
                <input type="hidden" name="space_id" value="{{ $selectedSpaceId }}">
            @endif
        </div>
        <div class="col-md-3">
            <label class="form-label" for="event_start">Event Start</label>
            <input type="text" name="event_start" id="event_start" class="form-control" x-ref="eventStart" placeholder="Select start" @if ($disabled || $booking) readonly @endif>
        </div>
        <div class="col-md-3">
            <label class="form-label" for="event_end">Event End</label>
            <input type="text" name="event_end" id="event_end" class="form-control" x-ref="eventEnd" placeholder="Select end" @if ($disabled || $booking) readonly @endif>
        </div>
        <div class="col-md-6">
            <label class="form-label" for="setup_start">Setup Start</label>
            <input type="text" name="setup_start" id="setup_start" class="form-control" x-model="setupStart" readonly>
        </div>
        <div class="col-md-6">
            <label class="form-label" for="breakdown_end">Breakdown End</label>
            <input type="text" name="breakdown_end" id="breakdown_end" class="form-control" x-model="breakdownEnd" readonly>
        </div>
        <div class="col-12">
            <div class="d-flex flex-wrap align-items-center gap-3">
                <div>
                    <span class="fw-medium">Availability:</span>
                    <span :class="statusClass" x-text="statusLabel" role="status" aria-live="polite"></span>
                </div>
                <div class="small text-muted d-flex gap-3">
                    <span><span class="vem-date-swatch vem-date-swatch--free"></span> Available</span>
                    <span><span class="vem-date-swatch vem-date-swatch--busy"></span> Unavailable</span>
                </div>
            </div>
        </div>
    </div>
</div>

@once
@push('styles')
<style>
    .vem-date-swatch { display: inline-block; width: 12px; height: 12px; border-radius: 2px; vertical-align: middle; margin-right: 4px; }
    .vem-date-swatch--free { background: #198754; }
    .vem-date-swatch--busy { background: #dc3545; }
    .flatpickr-day.vem-busy {
        background: #f8d7da !important;
        border-color: #f1aeb5 !important;
        color: #842029 !important;
    }
    .flatpickr-day.vem-free {
        background: #d1e7dd !important;
        border-color: #a3cfbb !important;
        color: #0f5132 !important;
    }
    .flatpickr-day.vem-busy:hover,
    .flatpickr-day.vem-free:hover {
        opacity: 0.9;
    }
</style>
@endpush

@push('scripts')
<script>
function spaceDatePicker(state, spaceMeta, busyUrl, checkUrl) {
    return {
        ...state,
        spaceMeta,
        busyUrl,
        checkUrl,
        startPicker: null,
        endPicker: null,
        init() {
            var self = this;
            if (typeof flatpickr === 'undefined') {
                console.warn('Flatpickr not loaded');
                return;
            }
            var common = {
                enableTime: true,
                time_24hr: true,
                dateFormat: 'Y-m-d\\TH:i',
                allowInput: true,
                onDayCreate: function (dObj, dStr, fp, dayElem) {
                    self.paintDay(dayElem);
                },
                onMonthChange: function () {
                    self.loadBusyDates();
                },
                onYearChange: function () {
                    self.loadBusyDates();
                }
            };
            this.startPicker = flatpickr(this.$refs.eventStart, Object.assign({}, common, {
                defaultDate: this.eventStart || null,
                onChange: function (selectedDates, dateStr) {
                    self.eventStart = dateStr;
                    self.onDatesChange();
                }
            }));
            this.endPicker = flatpickr(this.$refs.eventEnd, Object.assign({}, common, {
                defaultDate: this.eventEnd || null,
                onChange: function (selectedDates, dateStr) {
                    self.eventEnd = dateStr;
                    self.onDatesChange();
                }
            }));
            if (this.spaceId) {
                this.loadBusyDates().then(function () {
                    self.onDatesChange();
                });
            }
        },
        paintDay(dayElem) {
            var y = dayElem.dateObj.getFullYear();
            var m = String(dayElem.dateObj.getMonth() + 1).padStart(2, '0');
            var d = String(dayElem.dateObj.getDate()).padStart(2, '0');
            var key = y + '-' + m + '-' + d;
            dayElem.classList.remove('vem-busy', 'vem-free');
            if (!this.spaceId) return;
            if (this.busyDates.indexOf(key) !== -1) {
                dayElem.classList.add('vem-busy');
                dayElem.title = 'Unavailable';
            } else {
                dayElem.classList.add('vem-free');
                dayElem.title = 'Available';
            }
        },
        onSpaceChange() {
            this.loadBusyDates().then(() => this.onDatesChange());
        },
        loadBusyDates() {
            var self = this;
            if (!this.spaceId) {
                this.busyDates = [];
                this.redraw();
                return Promise.resolve();
            }
            var monthStart = this.startPicker ? this.startPicker.currentYear + '-' + String(this.startPicker.currentMonth + 1).padStart(2, '0') + '-01' : null;
            var start = monthStart || new Date().toISOString().slice(0, 8) + '01';
            var endDate = new Date(start);
            endDate.setMonth(endDate.getMonth() + 3);
            var end = endDate.toISOString().slice(0, 10);
            var params = new URLSearchParams({
                space_id: this.spaceId,
                start: start,
                end: end
            });
            return fetch(this.busyUrl + '?' + params.toString(), {
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
            })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    self.busyDates = data.busy_dates || [];
                    self.redraw();
                })
                .catch(function () {
                    self.busyDates = [];
                });
        },
        redraw() {
            if (this.startPicker) this.startPicker.redraw();
            if (this.endPicker) this.endPicker.redraw();
        },
        onDatesChange() {
            this.recalculateSetupBreakdown();
            this.checkAvailability();
            window.dispatchEvent(new CustomEvent('vem-dates-changed', {
                detail: {
                    eventStart: this.eventStart,
                    eventEnd: this.eventEnd,
                    guestCount: document.querySelector('[name="guest_count"]')?.value
                }
            }));
        },
        recalculateSetupBreakdown() {
            if (!this.spaceId || !this.eventStart || !this.eventEnd) return;
            var meta = this.spaceMeta[this.spaceId];
            if (!meta) return;
            var start = new Date(this.eventStart);
            var end = new Date(this.eventEnd);
            if (isNaN(start) || isNaN(end)) return;
            var setup = new Date(start.getTime() - (meta.setup || 0) * 60000);
            var breakdown = new Date(end.getTime() + (meta.breakdown || 0) * 60000);
            this.setupStart = this.toLocalInput(setup);
            this.breakdownEnd = this.toLocalInput(breakdown);
        },
        toLocalInput(date) {
            var pad = function (n) { return String(n).padStart(2, '0'); };
            return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate())
                + 'T' + pad(date.getHours()) + ':' + pad(date.getMinutes());
        },
        checkAvailability() {
            var self = this;
            if (!this.spaceId || !this.setupStart || !this.breakdownEnd) {
                this.statusLabel = 'Select space and dates';
                this.statusClass = 'text-muted';
                return;
            }
            var params = new URLSearchParams({
                space_id: this.spaceId,
                setup_start: this.setupStart,
                breakdown_end: this.breakdownEnd
            });
            fetch(this.checkUrl + '?' + params.toString(), {
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
            })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    self.statusLabel = data.label || (data.available ? 'Available' : 'Occupied');
                    self.statusClass = data.available ? 'text-success fw-semibold' : 'text-danger fw-semibold';
                })
                .catch(function () {
                    self.statusLabel = 'Unable to check availability';
                    self.statusClass = 'text-warning';
                });
        }
    };
}
</script>
@endpush
@endonce
