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

@php
    $statusVariants = [
        'active' => 'success',
        'inactive' => 'muted',
        'draft' => 'warning',
    ];

    $sortOptions = [
        'newest' => 'Newest',
        'name' => 'Name',
        'price_asc' => 'Price: Low to High',
        'price_desc' => 'Price: High to Low',
        'duration_asc' => 'Shortest Duration',
    ];

    $hasActiveFilters = collect($filters ?? [])->filter()->isNotEmpty();
@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 bookable services, pricing, timing, buffers, and staff assignments.</p>
            <x-ui.button href="{{ route('admin.services.create') }}">
                <x-ui.icon name="plus" class="h-4 w-4" />
                Add Service
            </x-ui.button>
        </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">
            <x-ui.card>
                <p class="text-sm font-semibold text-slate-600">Total Services</p>
                <p class="mt-3 text-3xl font-extrabold">{{ $stats['total'] }}</p>
                <p class="mt-4 text-xs font-semibold text-booklio-muted">Across {{ count($categories) }} categories</p>
            </x-ui.card>
            <x-ui.card>
                <p class="text-sm font-semibold text-slate-600">Active</p>
                <p class="mt-3 text-3xl font-extrabold">{{ $stats['active'] }}</p>
                <p class="mt-4 text-xs font-semibold text-emerald-600">Visible on booking page</p>
            </x-ui.card>
            <x-ui.card>
                <p class="text-sm font-semibold text-slate-600">Average Price</p>
                <p class="mt-3 text-3xl font-extrabold">${{ number_format($stats['average_price'], 0) }}</p>
                <p class="mt-4 text-xs font-semibold text-booklio-muted">Current service catalog</p>
            </x-ui.card>
            <x-ui.card>
                <p class="text-sm font-semibold text-slate-600">Top Service</p>
                <p class="mt-3 truncate text-xl font-extrabold">{{ $stats['top_service']?->name ?? 'No service yet' }}</p>
                <p class="mt-4 text-xs font-semibold text-booklio-muted">{{ $stats['top_service']?->appointments_count ?? 0 }} bookings</p>
            </x-ui.card>
        </section>

        <x-ui.card>
            <form method="GET" action="{{ route('admin.services.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 service name, category, staff..." />
                </div>
                <select name="category" 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 Categories</option>
                    @foreach ($categories as $categoryValue => $categoryLabel)
                        <option value="{{ $categoryValue }}" @selected(($filters['category'] ?? '') === $categoryValue)>{{ $categoryLabel }}</option>
                    @endforeach
                </select>
                <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 (\App\Models\Service::STATUSES 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="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'] ?? 'newest') === $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.services.index') }}">Reset</x-ui.button>
                @endif
            </form>
        </x-ui.card>

        <x-ui.card title="Service List" padding="p-0">
            @if ($services->isNotEmpty())
            <div class="hidden overflow-x-auto md:block booklio-scrollbar">
                <table class="min-w-[1280px] w-full divide-y divide-booklio-border">
                    <thead class="bg-slate-50">
                        <tr>
                            @foreach (['Service', 'Category', 'Price', 'Duration', 'Assigned Staff', 'Buffer Time', 'Status', '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 ($services as $service)
                            @php
                                $staffNames = $service->staffProfiles->pluck('name')->join(', ') ?: 'Unassigned';
                                $bufferLabel = $service->buffer_before_minutes . 'm before / ' . $service->buffer_after_minutes . 'm after';
                            @endphp
                            <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-11 w-11 items-center justify-center rounded-lg bg-blue-50 text-booklio-primary">
                                            <x-ui.icon name="sparkles" class="h-5 w-5" />
                                        </div>
                                        <div class="min-w-0">
                                            <p class="max-w-[220px] truncate text-sm font-extrabold text-booklio-dark">{{ $service->name }}</p>
                                            <p class="text-xs font-medium text-booklio-muted">{{ $service->appointments_count }} bookings</p>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-5 py-4 text-sm font-semibold text-slate-700"><span class="block max-w-[180px] truncate">{{ $service->category ?: 'Uncategorized' }}</span></td>
                                <td class="px-5 py-4 text-sm font-extrabold text-booklio-dark">${{ number_format($service->price, 2) }}</td>
                                <td class="px-5 py-4 text-sm font-semibold text-slate-700">{{ $service->duration_minutes }} min</td>
                                <td class="px-5 py-4 text-sm font-semibold text-slate-700"><span class="block max-w-[220px] break-words">{{ $staffNames }}</span></td>
                                <td class="px-5 py-4 text-sm font-medium text-booklio-muted">{{ $bufferLabel }}</td>
                                <td class="px-5 py-4"><x-ui.badge :variant="$statusVariants[$service->status] ?? 'muted'">{{ $service->status_label }}</x-ui.badge></td>
                                <td class="px-5 py-4">
                                    <div class="flex flex-wrap items-center gap-2">
                                        <x-ui.button size="sm" variant="secondary" href="{{ route('admin.services.show', $service) }}">View</x-ui.button>
                                        <x-ui.button size="sm" variant="ghost" href="{{ route('admin.services.edit', $service) }}">Edit</x-ui.button>
                                        <button type="button" data-modal-open="#delete-service-modal-{{ $service->id }}" class="inline-flex h-9 items-center justify-center rounded-lg px-3 text-xs font-bold text-booklio-danger transition hover:bg-red-50">Delete</button>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>

            <div class="divide-y divide-booklio-border md:hidden">
                @foreach ($services as $service)
                    @php
                        $staffNames = $service->staffProfiles->pluck('name')->join(', ') ?: 'Unassigned';
                        $bufferLabel = $service->buffer_before_minutes . 'm / ' . $service->buffer_after_minutes . 'm';
                    @endphp
                    <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-11 w-11 shrink-0 items-center justify-center rounded-lg bg-blue-50 text-booklio-primary">
                                    <x-ui.icon name="sparkles" class="h-5 w-5" />
                                </div>
                                <div class="min-w-0">
                                    <p class="truncate text-sm font-extrabold">{{ $service->name }}</p>
                                    <p class="truncate text-xs font-medium text-booklio-muted">{{ $service->category ?: 'Uncategorized' }}</p>
                                </div>
                            </div>
                            <x-ui.badge :variant="$statusVariants[$service->status] ?? 'muted'">{{ $service->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">Price</p><p class="font-bold">${{ number_format($service->price, 2) }}</p></div>
                            <div><p class="text-xs font-bold text-booklio-muted">Duration</p><p class="font-bold">{{ $service->duration_minutes }} min</p></div>
                            <div><p class="text-xs font-bold text-booklio-muted">Staff</p><p class="font-bold">{{ $staffNames }}</p></div>
                            <div><p class="text-xs font-bold text-booklio-muted">Buffer</p><p class="font-bold">{{ $bufferLabel }}</p></div>
                        </div>
                        <div class="mt-4 grid grid-cols-3 gap-2">
                            <x-ui.button size="sm" variant="secondary" href="{{ route('admin.services.show', $service) }}">View</x-ui.button>
                            <x-ui.button size="sm" variant="ghost" href="{{ route('admin.services.edit', $service) }}">Edit</x-ui.button>
                            <button type="button" data-modal-open="#delete-service-modal-{{ $service->id }}" class="inline-flex h-9 items-center justify-center rounded-lg px-3 text-xs font-bold text-booklio-danger transition hover:bg-red-50">Delete</button>
                        </div>
                    </div>
                @endforeach
            </div>

            <div class="border-t border-booklio-border px-5 py-4">
                <x-ui.pagination :paginator="$services" />
            </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="sparkles" class="h-7 w-7" />
                        </div>
                        <h3 class="mt-4 text-base font-extrabold text-booklio-dark">No services found</h3>
                        <p class="mt-2 text-sm leading-6 text-booklio-muted">{{ $hasActiveFilters ? 'No services match the current filters. Reset filters or create a new service.' : 'Create your first service so customers can book from the public booking page.' }}</p>
                        <x-ui.button href="{{ route('admin.services.create') }}" class="mt-5">Add Service</x-ui.button>
                    </div>
                </div>
            @endif
        </x-ui.card>
    </div>

    @push('modals')
        @foreach ($services as $service)
            @include('admin.services.partials.delete-modal', ['service' => $service, 'modalId' => 'delete-service-modal-' . $service->id])
        @endforeach
    @endpush
@endsection
