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

@php
    $statusVariants = [
        'active' => 'success',
        'vip' => 'primary',
        'new' => 'purple',
        'inactive' => 'muted',
    ];

    $sortOptions = [
        'newest' => 'Newest',
        'name' => 'Name',
        'spent_desc' => 'Highest Spent',
        'last_visit_desc' => 'Last Visit',
    ];

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

    $summaryCards = [
        ['label' => 'Total Customers', 'value' => number_format($summary['total']), 'note' => 'CRM profiles in this business', 'icon' => 'users', 'class' => 'bg-blue-50 text-booklio-primary'],
        ['label' => 'Returning Rate', 'value' => $summary['returning_rate'] . '%', 'note' => 'Customers with 2+ bookings', 'icon' => 'check', 'class' => 'bg-emerald-50 text-emerald-600'],
        ['label' => 'Outstanding Due', 'value' => '$' . number_format($summary['outstanding_due'], 2), 'note' => $summary['unpaid_invoices'] . ' unpaid invoices', 'icon' => 'file-text', 'class' => 'bg-amber-50 text-amber-600'],
        ['label' => 'VIP Customers', 'value' => number_format($summary['vip']), 'note' => 'High-value profiles', 'icon' => 'user', 'class' => 'bg-violet-50 text-violet-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 customer profiles, appointment history, invoices, and notes.</p>
            <x-ui.button data-modal-open="#add-customer-modal">
                <x-ui.icon name="plus" class="h-4 w-4" />
                Add Customer
            </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">
            @foreach ($summaryCards 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 truncate 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.customers.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 name, phone, email..." />
                </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 (\App\Models\Customer::STATUSES as $statusValue => $statusLabel)
                        <option value="{{ $statusValue }}" @selected(($filters['status'] ?? '') === $statusValue)>{{ $statusLabel }}</option>
                    @endforeach
                </select>
                <select name="source" 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 Sources</option>
                    @foreach ($sources as $source)
                        <option value="{{ $source }}" @selected(($filters['source'] ?? '') === $source)>{{ $source }}</option>
                    @endforeach
                </select>
                <select name="balance" 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 Balances</option>
                    <option value="has_due" @selected(($filters['balance'] ?? '') === 'has_due')>Has due</option>
                    <option value="no_due" @selected(($filters['balance'] ?? '') === 'no_due')>No due</option>
                </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.customers.index') }}">Reset</x-ui.button>
                @endif
            </form>
        </x-ui.card>

        <x-ui.card title="Customer List" padding="p-0">
            @if ($customers->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', 'Contact', 'Status', 'Last Visit', 'Appointments', 'Total Spent', 'Due', 'Source', '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 ($customers as $customer)
                                @php
                                    $due = (float) ($customer->due_total ?? 0);
                                @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 shrink-0 items-center justify-center rounded-full bg-blue-50 text-xs font-extrabold text-booklio-primary">{{ $customer->initials }}</div>
                                            <div class="min-w-0">
                                                <p class="truncate text-sm font-extrabold text-booklio-dark">{{ $customer->name }}</p>
                                                <p class="text-xs font-medium text-booklio-muted">Customer #{{ 1000 + $customer->id }}</p>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-5 py-4">
                                        <p class="max-w-[180px] truncate text-sm font-semibold text-booklio-dark">{{ $customer->phone ?: 'No phone' }}</p>
                                        <p class="max-w-[220px] truncate text-xs font-medium text-booklio-muted">{{ $customer->email ?: 'No email' }}</p>
                                    </td>
                                    <td class="px-5 py-4"><x-ui.badge :variant="$statusVariants[$customer->status] ?? 'muted'">{{ $customer->status_label }}</x-ui.badge></td>
                                    <td class="px-5 py-4 text-sm font-semibold text-slate-700">{{ $customer->last_visit_at?->format('M d, Y') ?? 'No visits yet' }}</td>
                                    <td class="px-5 py-4 text-sm font-extrabold">{{ $customer->appointments_count }}</td>
                                    <td class="px-5 py-4 text-sm font-extrabold">${{ number_format((float) $customer->total_spent, 2) }}</td>
                                    <td class="px-5 py-4 text-sm font-extrabold {{ $due > 0 ? 'text-booklio-danger' : 'text-booklio-dark' }}">${{ number_format($due, 2) }}</td>
                                    <td class="max-w-[180px] truncate px-5 py-4 text-sm font-semibold text-slate-700">{{ $customer->source ?: 'Manual' }}</td>
                                    <td class="px-5 py-4">
                                        <div class="flex items-center gap-2">
                                            <x-ui.button size="sm" variant="secondary" href="{{ route('admin.customers.show', $customer) }}">View</x-ui.button>
                                            <x-ui.button size="sm" variant="ghost" data-modal-open="#edit-customer-modal-{{ $customer->id }}">Edit</x-ui.button>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                <div class="divide-y divide-booklio-border md:hidden">
                    @foreach ($customers as $customer)
                        @php
                            $due = (float) ($customer->due_total ?? 0);
                        @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-full bg-blue-50 text-xs font-extrabold text-booklio-primary">{{ $customer->initials }}</div>
                                    <div class="min-w-0">
                                        <p class="truncate text-sm font-extrabold">{{ $customer->name }}</p>
                                        <p class="truncate text-xs font-medium text-booklio-muted">{{ $customer->phone ?: $customer->email ?: 'No contact yet' }}</p>
                                    </div>
                                </div>
                                <x-ui.badge :variant="$statusVariants[$customer->status] ?? 'muted'">{{ $customer->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">Appointments</p><p class="font-bold">{{ $customer->appointments_count }}</p></div>
                                <div><p class="text-xs font-bold text-booklio-muted">Spent</p><p class="font-bold">${{ number_format((float) $customer->total_spent, 2) }}</p></div>
                                <div><p class="text-xs font-bold text-booklio-muted">Due</p><p class="font-bold {{ $due > 0 ? 'text-booklio-danger' : '' }}">${{ number_format($due, 2) }}</p></div>
                                <div><p class="text-xs font-bold text-booklio-muted">Last Visit</p><p class="font-bold">{{ $customer->last_visit_at?->format('M d, Y') ?? 'No visits' }}</p></div>
                            </div>
                            <div class="mt-4 grid grid-cols-2 gap-2">
                                <x-ui.button size="sm" variant="secondary" href="{{ route('admin.customers.show', $customer) }}">View</x-ui.button>
                                <x-ui.button size="sm" variant="ghost" data-modal-open="#edit-customer-modal-{{ $customer->id }}">Edit</x-ui.button>
                            </div>
                        </div>
                    @endforeach
                </div>

                <div class="border-t border-booklio-border px-5 py-4">
                    <x-ui.pagination :paginator="$customers" />
                </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="users" class="h-7 w-7" />
                        </div>
                        <h3 class="mt-4 text-base font-extrabold text-booklio-dark">No customers found</h3>
                        <p class="mt-2 text-sm leading-6 text-booklio-muted">{{ $hasActiveFilters ? 'No customers match the current filters. Reset filters or add a new customer.' : 'Create your first customer profile to track bookings, invoices, and notes.' }}</p>
                        <x-ui.button data-modal-open="#add-customer-modal" class="mt-5">Add Customer</x-ui.button>
                    </div>
                </div>
            @endif
        </x-ui.card>
    </div>

    @push('modals')
        @include('admin.customers.partials.add-modal')
        @foreach ($customers as $customer)
            @include('admin.customers.partials.edit-modal', ['customer' => $customer, 'modalId' => 'edit-customer-modal-' . $customer->id])
        @endforeach
    @endpush
@endsection
