@extends('layouts.admin', [
    'title' => 'Appointment Calendar',
    'pageTitle' => 'Appointment Calendar',
    'active' => 'calendar',
])

@php
    $statusVariants = [
        'pending' => 'warning',
        'confirmed' => 'primary',
        'checked_in' => 'purple',
        'completed' => 'success',
        'cancelled' => 'danger',
        'no_show' => 'muted',
    ];

    $blockClasses = [
        'pending' => 'border-amber-200 bg-amber-50/95 text-amber-800',
        'confirmed' => 'border-blue-200 bg-blue-50/95 text-blue-800',
        'checked_in' => 'border-violet-200 bg-violet-50/95 text-violet-800',
        'completed' => 'border-emerald-200 bg-emerald-50/95 text-emerald-800',
        'cancelled' => 'border-red-200 bg-red-50/95 text-red-700',
        'no_show' => 'border-slate-200 bg-slate-50/95 text-slate-700',
    ];

    $columnCount = max(1, $staffProfiles->count());
    $startHour = min($calendarHours);
    $endHour = max($calendarHours);
    $dayStart = $selectedDate->copy()->setTime($startHour, 0);
    $previousDate = $selectedDate->copy()->subDay()->toDateString();
    $nextDate = $selectedDate->copy()->addDay()->toDateString();
@endphp

@section('content')
    <div class="space-y-5">
        <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <p class="text-sm font-medium text-booklio-muted">Review staff availability, time slots, and daily appointment flow.</p>
            <div class="flex flex-col gap-3 sm:flex-row">
                <x-ui.button variant="secondary" href="{{ route('admin.appointments.index') }}">
                    <x-ui.icon name="briefcase" class="h-4 w-4" />
                    List View
                </x-ui.button>
                <x-ui.button data-modal-open="#create-appointment-modal">
                    <x-ui.icon name="plus" class="h-4 w-4" />
                    New Appointment
                </x-ui.button>
            </div>
        </div>

        @if (session('status'))
            <div class="rounded-lg border border-emerald-100 bg-emerald-50 px-4 py-3 text-sm font-bold text-emerald-700">
                {{ session('status') }}
            </div>
        @endif

        <x-ui.card>
            <form method="GET" action="{{ route('admin.appointments.calendar') }}" class="booklio-filter-grid">
                <div class="relative">
                    <x-ui.icon name="search" class="pointer-events-none absolute right-3 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
                    <input name="q" value="{{ $filters['q'] ?? '' }}" class="h-11 w-full rounded-lg border border-booklio-border bg-white pl-4 pr-11 text-sm font-medium shadow-soft outline-none placeholder:text-slate-400 focus:border-booklio-primary focus:ring-4 focus:ring-blue-100" placeholder="Search appointments..." />
                </div>
                <select name="staff_profile_id" class="h-11 rounded-lg border border-booklio-border bg-white px-3 text-sm font-semibold text-slate-700 shadow-soft outline-none focus:border-booklio-primary focus:ring-4 focus:ring-blue-100">
                    <option value="">All Staff</option>
                    @foreach ($staffProfiles as $staff)
                        <option value="{{ $staff->id }}" @selected((string) ($filters['staff_profile_id'] ?? '') === (string) $staff->id)>{{ $staff->name }}</option>
                    @endforeach
                </select>
                <input name="date" value="{{ $selectedDate->toDateString() }}" type="date" class="h-11 rounded-lg border border-booklio-border bg-white px-3 text-sm font-semibold text-slate-700 shadow-soft outline-none focus:border-booklio-primary focus:ring-4 focus:ring-blue-100" />
                <div class="inline-flex overflow-hidden rounded-lg border border-booklio-border bg-white shadow-soft">
                    <a href="{{ route('admin.appointments.calendar', ['date' => $previousDate, 'staff_profile_id' => $filters['staff_profile_id'] ?? null, 'q' => $filters['q'] ?? null]) }}" class="flex h-11 w-11 items-center justify-center hover:bg-slate-50"><x-ui.icon name="chevron-left" class="h-4 w-4" /></a>
                    <span class="flex h-11 items-center border-x border-booklio-border px-6 text-sm font-bold">{{ $selectedDate->format('M d, Y') }}</span>
                    <a href="{{ route('admin.appointments.calendar', ['date' => $nextDate, 'staff_profile_id' => $filters['staff_profile_id'] ?? null, 'q' => $filters['q'] ?? null]) }}" class="flex h-11 w-11 items-center justify-center hover:bg-slate-50"><x-ui.icon name="chevron-right" class="h-4 w-4" /></a>
                </div>
                <x-ui.button variant="secondary" type="submit">
                    <x-ui.icon name="filter" class="h-4 w-4" />
                    Filter
                </x-ui.button>
            </form>
        </x-ui.card>

        <section class="grid gap-5 xl:grid-cols-[minmax(0,1fr)_360px]">
            <x-ui.card title="Daily Schedule" padding="p-0" class="overflow-hidden">
                <div class="overflow-x-auto p-5 booklio-scrollbar">
                    <div class="min-w-[680px]">
                        <div class="grid items-center pb-3" style="grid-template-columns: 56px repeat({{ $columnCount }}, minmax(150px, 1fr));">
                            <div></div>
                            @forelse ($staffProfiles as $member)
                                <div class="flex items-center justify-center gap-3">
                                    <div class="flex h-8 w-8 items-center justify-center rounded-full bg-blue-50 text-[11px] font-extrabold text-booklio-primary ring-2 ring-white">{{ $member->initials }}</div>
                                    <span class="truncate text-sm font-bold text-slate-700">{{ $member->name }}</span>
                                </div>
                            @empty
                                <div class="text-center text-sm font-bold text-booklio-muted">No staff</div>
                            @endforelse
                        </div>

                        <div class="relative grid border-t border-booklio-border" style="grid-template-columns: 56px repeat({{ $columnCount }}, minmax(150px, 1fr));">
                            @foreach ($calendarHours as $hour)
                                <div class="h-[62px] border-b border-booklio-border pr-3 pt-3 text-right text-xs font-bold text-slate-600">{{ \Illuminate\Support\Carbon::createFromTime($hour)->format('g A') }}</div>
                                @foreach ($staffProfiles as $member)
                                    <div class="h-[62px] border-b border-l border-booklio-border"></div>
                                @endforeach
                            @endforeach

                            @foreach ($appointments as $item)
                                @php
                                    $staffIndex = $staffProfiles->values()->search(fn ($member) => (int) $member->id === (int) $item->staff_profile_id);
                                    $minutesFromStart = $item->starts_at->diffInMinutes($dayStart, false) * -1;
                                    $top = max(0, $minutesFromStart * (62 / 60));
                                    $height = max(44, $item->duration_minutes * (62 / 60));
                                @endphp
                                @if ($staffIndex !== false && $item->starts_at->hour <= $endHour)
                                    <a href="{{ route('admin.appointments.show', $item) }}" class="absolute z-10 overflow-hidden rounded-lg border p-3 shadow-soft {{ $blockClasses[$item->status_value] ?? $blockClasses['confirmed'] }}" style="left: calc(56px + ((100% - 56px) / {{ $columnCount }}) * {{ $staffIndex }} + 12px); top: {{ $top }}px; width: calc(((100% - 56px) / {{ $columnCount }}) - 24px); height: {{ $height }}px;">
                                        <p class="truncate text-sm font-extrabold">{{ $item->service?->name ?? 'Service removed' }}</p>
                                        <p class="mt-1 truncate text-xs font-medium text-slate-700">{{ $item->starts_at->format('g:i A') }} - {{ $item->ends_at->format('g:i A') }}</p>
                                        <p class="mt-1 truncate text-xs font-medium text-slate-600">{{ $item->customer?->name ?? 'Customer removed' }}</p>
                                    </a>
                                @endif
                            @endforeach
                        </div>
                    </div>
                </div>
            </x-ui.card>

            <div class="space-y-5">
                <x-ui.card title="Today's Appointments">
                    <div class="space-y-3">
                        @forelse ($appointments as $item)
                            <div class="rounded-lg border border-booklio-border p-3">
                                <div class="flex items-start justify-between gap-3">
                                    <div class="flex min-w-0 items-center gap-3">
                                        <div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-blue-50 text-xs font-extrabold text-booklio-primary">{{ $item->customer?->initials ?? 'CU' }}</div>
                                        <div class="min-w-0">
                                            <p class="truncate text-sm font-extrabold">{{ $item->customer?->name ?? 'Customer removed' }}</p>
                                            <p class="truncate text-xs font-medium text-booklio-muted">{{ $item->service?->name ?? 'Service removed' }}</p>
                                        </div>
                                    </div>
                                    <x-ui.badge :variant="$statusVariants[$item->status_value] ?? 'muted'">{{ $item->status_label }}</x-ui.badge>
                                </div>
                                <div class="mt-3 flex items-center justify-between text-xs font-bold text-slate-600">
                                    <span>{{ $item->starts_at->format('g:i A') }}</span>
                                    <button type="button" data-modal-open="#status-appointment-modal-{{ $item->id }}" class="text-booklio-primary">Update</button>
                                </div>
                            </div>
                        @empty
                            <div class="rounded-lg border border-dashed border-booklio-border p-5 text-sm font-medium text-booklio-muted">No appointments for this day.</div>
                        @endforelse
                    </div>
                </x-ui.card>

                <x-ui.card title="Calendar Legend">
                    <div class="grid gap-3 text-sm font-semibold text-slate-700">
                        <div class="flex items-center gap-2"><span class="h-3 w-3 rounded-full bg-blue-500"></span> Confirmed</div>
                        <div class="flex items-center gap-2"><span class="h-3 w-3 rounded-full bg-violet-500"></span> Checked In</div>
                        <div class="flex items-center gap-2"><span class="h-3 w-3 rounded-full bg-amber-500"></span> Pending</div>
                        <div class="flex items-center gap-2"><span class="h-3 w-3 rounded-full bg-emerald-500"></span> Completed</div>
                    </div>
                </x-ui.card>
            </div>
        </section>
    </div>

    @push('modals')
        @include('admin.appointments.partials.create-modal', ['modalAppointment' => null, 'mode' => 'create', 'modalId' => 'create-appointment-modal'])
        @foreach ($appointments as $item)
            @include('admin.appointments.partials.status-modal', ['modalAppointment' => $item, 'modalId' => 'status-appointment-modal-' . $item->id])
        @endforeach
    @endpush
@endsection
