@extends('layouts.admin', [
    'title' => 'Appointments',
    'pageTitle' => 'Appointments',
    'active' => 'appointments',
])

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

    $sortOptions = [
        'upcoming' => 'Upcoming',
        'newest' => 'Newest',
        'oldest' => 'Oldest',
    ];

    $hasActiveFilters = collect($filters ?? [])
        ->filter(fn ($value, $key) => filled($value) && ! ($key === 'sort' && $value === 'upcoming'))
        ->isNotEmpty();

    $summary = [
        ['label' => 'Today', 'value' => $stats['today'], 'note' => $stats['remaining_today'] . ' remaining', 'icon' => 'calendar-days', 'class' => 'bg-blue-50 text-booklio-primary'],
        ['label' => 'Confirmed', 'value' => $stats['confirmed_week'], 'note' => 'This week', 'icon' => 'check', 'class' => 'bg-emerald-50 text-emerald-600'],
        ['label' => 'Pending', 'value' => $stats['pending'], 'note' => 'Needs review', 'icon' => 'clock', 'class' => 'bg-amber-50 text-amber-600'],
        ['label' => 'No Show', 'value' => $stats['no_show_7_days'], 'note' => 'Last 7 days', 'icon' => 'x', 'class' => 'bg-red-50 text-red-600'],
    ];
@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">Manage bookings, status updates, and customer check-ins.</p>
            <div class="flex flex-col gap-3 sm:flex-row">
                <x-ui.button variant="secondary" href="{{ route('admin.appointments.calendar') }}">
                    <x-ui.icon name="calendar-days" class="h-4 w-4" />
                    Calendar 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

        <section class="grid gap-5 sm:grid-cols-2 xl:grid-cols-4">
            @foreach ($summary as $item)
                <x-ui.card class="min-w-0 overflow-hidden">
                    <div class="flex items-start justify-between gap-4">
                        <div class="min-w-0">
                            <p class="truncate text-sm font-semibold text-slate-600">{{ $item['label'] }}</p>
                            <p class="mt-3 text-3xl font-extrabold leading-none">{{ $item['value'] }}</p>
                            <p class="mt-4 truncate text-xs font-semibold text-booklio-muted">{{ $item['note'] }}</p>
                        </div>
                        <div class="hidden h-12 w-12 shrink-0 items-center justify-center rounded-xl sm:flex {{ $item['class'] }}">
                            <x-ui.icon :name="$item['icon']" class="h-6 w-6" />
                        </div>
                    </div>
                </x-ui.card>
            @endforeach
        </section>

        <x-ui.card>
            <form method="GET" action="{{ route('admin.appointments.index') }}" 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 customer, phone, service..." />
                </div>
                <select name="status" 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 Statuses</option>
                    @foreach ($statusOptions as $statusValue => $statusLabel)
                        <option value="{{ $statusValue }}" @selected(($filters['status'] ?? '') === $statusValue)>{{ $statusLabel }}</option>
                    @endforeach
                </select>
                <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>
                <select name="service_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 Services</option>
                    @foreach ($services as $service)
                        <option value="{{ $service->id }}" @selected((string) ($filters['service_id'] ?? '') === (string) $service->id)>{{ $service->name }}</option>
                    @endforeach
                </select>
                <input name="date" value="{{ $filters['date'] ?? '' }}" 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" />
                <select name="sort" 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">
                    @foreach ($sortOptions as $sortValue => $sortLabel)
                        <option value="{{ $sortValue }}" @selected(($filters['sort'] ?? 'upcoming') === $sortValue)>{{ $sortLabel }}</option>
                    @endforeach
                </select>
                <x-ui.button variant="secondary" type="submit">
                    <x-ui.icon name="filter" class="h-4 w-4" />
                    Filter
                </x-ui.button>
                @if ($hasActiveFilters)
                    <x-ui.button variant="ghost" href="{{ route('admin.appointments.index') }}">Reset</x-ui.button>
                @endif
            </form>
        </x-ui.card>

        <x-ui.card title="Appointment List" padding="p-0">
            @if ($appointments->isNotEmpty())
                <div class="hidden overflow-x-auto md:block booklio-scrollbar">
                    <table class="min-w-[1320px] w-full divide-y divide-booklio-border">
                        <thead class="bg-slate-50">
                            <tr>
                                @foreach (['Customer', 'Service', 'Staff', 'Date & Time', 'Status', 'Payment', 'Actions'] as $heading)
                                    <th class="px-5 py-4 text-left text-xs font-bold uppercase tracking-wide text-booklio-muted">{{ $heading }}</th>
                                @endforeach
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-booklio-border bg-white">
                            @foreach ($appointments as $item)
                                <tr class="transition hover:bg-slate-50/80">
                                    <td class="px-5 py-4">
                                        <div class="flex 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 text-booklio-dark">{{ $item->customer?->name ?? 'Customer removed' }}</p>
                                                <p class="truncate text-xs font-medium text-booklio-muted">{{ $item->customer?->phone ?? $item->customer?->email ?? $item->booking_number }}</p>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="max-w-[220px] truncate px-5 py-4 text-sm font-semibold text-slate-700">{{ $item->service?->name ?? 'Service removed' }}</td>
                                    <td class="max-w-[180px] truncate px-5 py-4 text-sm font-semibold text-slate-700">{{ $item->staffProfile?->name ?? 'Unassigned' }}</td>
                                    <td class="px-5 py-4">
                                        <p class="text-sm font-bold text-booklio-dark">{{ $item->starts_at?->format('M d, Y') }}</p>
                                        <p class="text-xs font-medium text-booklio-muted">{{ $item->starts_at?->format('g:i A') }} - {{ $item->ends_at?->format('g:i A') }}</p>
                                    </td>
                                    <td class="px-5 py-4">
                                        <x-ui.badge :variant="$statusVariants[$item->status_value] ?? 'muted'">{{ $item->status_label }}</x-ui.badge>
                                    </td>
                                    <td class="px-5 py-4">
                                        <p class="text-sm font-bold text-booklio-dark">${{ number_format((float) $item->price, 2) }}</p>
                                        <p class="text-xs font-medium capitalize text-booklio-muted">{{ str_replace('_', ' ', $item->payment_status) }}</p>
                                    </td>
                                    <td class="px-5 py-4">
                                        <div class="flex items-center gap-2">
                                            <x-ui.button size="sm" variant="secondary" href="{{ route('admin.appointments.show', $item) }}">View</x-ui.button>
                                            <x-ui.button size="sm" variant="ghost" data-modal-open="#status-appointment-modal-{{ $item->id }}">Status</x-ui.button>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                <div class="divide-y divide-booklio-border md:hidden">
                    @foreach ($appointments as $item)
                        <div class="p-5">
                            <div class="flex items-start justify-between gap-4">
                                <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-4 grid grid-cols-2 gap-3 text-sm">
                                <div><p class="text-xs font-bold text-booklio-muted">Date</p><p class="font-bold">{{ $item->starts_at?->format('M d, Y') }}</p></div>
                                <div><p class="text-xs font-bold text-booklio-muted">Time</p><p class="font-bold">{{ $item->starts_at?->format('g:i A') }}</p></div>
                                <div><p class="text-xs font-bold text-booklio-muted">Staff</p><p class="font-bold">{{ $item->staffProfile?->name ?? 'Unassigned' }}</p></div>
                                <div><p class="text-xs font-bold text-booklio-muted">Amount</p><p class="font-bold">${{ number_format((float) $item->price, 2) }}</p></div>
                            </div>
                            <div class="mt-4 grid grid-cols-2 gap-2">
                                <x-ui.button size="sm" variant="secondary" href="{{ route('admin.appointments.show', $item) }}">View</x-ui.button>
                                <x-ui.button size="sm" variant="ghost" data-modal-open="#status-appointment-modal-{{ $item->id }}">Status</x-ui.button>
                            </div>
                        </div>
                    @endforeach
                </div>

                <div class="border-t border-booklio-border px-5 py-4">
                    <x-ui.pagination :paginator="$appointments" />
                </div>
            @else
                <div class="p-8">
                    <div class="mx-auto max-w-md text-center">
                        <div class="mx-auto flex h-14 w-14 items-center justify-center rounded-xl bg-blue-50 text-booklio-primary">
                            <x-ui.icon name="calendar-days" class="h-7 w-7" />
                        </div>
                        <h3 class="mt-4 text-base font-extrabold text-booklio-dark">No appointments found</h3>
                        <p class="mt-2 text-sm leading-6 text-booklio-muted">{{ $hasActiveFilters ? 'No appointments match the current filters.' : 'Create the first appointment for this business.' }}</p>
                        <x-ui.button data-modal-open="#create-appointment-modal" class="mt-5">New Appointment</x-ui.button>
                    </div>
                </div>
            @endif
        </x-ui.card>
    </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
