{# app/templates/admin/customers.html #}
{% extends "admin/base.html" %}
{% from 'shared/macros/headers.html' import page_header_flex, refresh_button %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/tables.html' import table_wrapper, table_header %}
{% from 'shared/macros/pagination.html' import pagination %}
{% from 'shared/macros/modals.html' import confirm_modal_dynamic %}
{% from 'shared/macros/inputs.html' import entity_selector, entity_selected_badge %}

{% block title %}Customers{% endblock %}

{% block alpine_data %}adminCustomers(){% endblock %}

{% block content %}
<!-- Page Header with Store Selector -->
{% call page_header_flex(title='Customer Management', subtitle='Manage customers across all stores') %}
    <div class="flex items-center gap-4">
        <!-- Store Autocomplete (Tom Select) -->
        {{ entity_selector(ref_name='storeSelect', id='store-select', placeholder='Filter by store...') }}
        {{ refresh_button(loading_var='loading', onclick='resetAndLoad()', variant='secondary') }}
    </div>
{% endcall %}

<!-- Selected Store Info -->
{{ entity_selected_badge(entity_var='selectedStore', clear_fn='clearStoreFilter()', code_field='store_code', color='purple') }}

{{ loading_state('Loading customers...') }}

{{ error_state('Error loading customers') }}

<!-- Stats Cards -->
<div x-show="!loading" class="grid gap-6 mb-8 md:grid-cols-2">
    <!-- Card: Total Customers -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
            <span x-html="$icon('user-group', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                Total Customers
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.total || 0">
                0
            </p>
        </div>
    </div>

    <!-- Card: Active Customers -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
            <span x-html="$icon('user-check', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                Active
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.active || 0">
                0
            </p>
        </div>
    </div>
</div>

<!-- Search and Filters -->
<div x-show="!loading" class="mb-6 px-4 py-3 bg-white rounded-lg shadow-md dark:bg-gray-800">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <!-- Search Bar -->
        <div class="flex-1 max-w-md">
            <div class="relative">
                <input
                    type="text"
                    x-model="filters.search"
                    @input.debounce.300ms="resetAndLoad()"
                    placeholder="Search by name, email, or customer number..."
                    class="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none focus:shadow-outline-purple dark:bg-gray-700 dark:text-gray-300"
                >
                <div class="absolute inset-y-0 left-0 flex items-center pl-3">
                    <span x-html="$icon('search', 'w-5 h-5 text-gray-400')"></span>
                </div>
            </div>
        </div>

        <!-- Status Filter -->
        <div class="flex items-center gap-4">
            <select
                x-model="filters.is_active"
                @change="resetAndLoad()"
                class="px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
            >
                <option value="">All Status</option>
                <option value="true">Active</option>
                <option value="false">Inactive</option>
            </select>
        </div>
    </div>
</div>

<!-- Customers Table -->
<div x-show="!loading" class="w-full overflow-hidden rounded-lg shadow-xs">
    <div class="w-full overflow-x-auto">
        <table class="w-full whitespace-no-wrap">
            <thead>
                <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
                    <th class="px-4 py-3">Customer</th>
                    <th class="px-4 py-3">Store</th>
                    <th class="px-4 py-3">Customer #</th>
                    <th class="px-4 py-3">Status</th>
                    <th class="px-4 py-3">Joined</th>
                    <th class="px-4 py-3">Actions</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                <!-- Loading state -->
                <template x-if="loadingCustomers && customers.length === 0">
                    <tr>
                        <td colspan="6" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                            <span x-html="$icon('spinner', 'w-6 h-6 mx-auto mb-2')"></span>
                            <p>Loading customers...</p>
                        </td>
                    </tr>
                </template>

                <!-- Empty state -->
                <template x-if="!loadingCustomers && customers.length === 0">
                    <tr>
                        <td colspan="6" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                            <span x-html="$icon('user-group', 'w-12 h-12 mx-auto mb-2 text-gray-300')"></span>
                            <p class="font-medium">No customers found</p>
                            <p class="text-sm mt-1">Try adjusting your search or filters</p>
                        </td>
                    </tr>
                </template>

                <!-- Customer rows -->
                <template x-for="customer in customers" :key="customer.id">
                    <tr class="text-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700">
                        <!-- Customer -->
                        <td class="px-4 py-3">
                            <div class="flex items-center text-sm">
                                <div class="relative hidden w-8 h-8 mr-3 rounded-full md:block bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
                                    <span x-html="$icon('user', 'w-4 h-4 text-gray-500')"></span>
                                </div>
                                <div>
                                    <p class="font-semibold" x-text="customer.first_name && customer.last_name ? customer.first_name + ' ' + customer.last_name : customer.email"></p>
                                    <p class="text-xs text-gray-600 dark:text-gray-400" x-text="customer.email"></p>
                                </div>
                            </div>
                        </td>

                        <!-- Store -->
                        <td class="px-4 py-3 text-sm">
                            <span x-text="customer.store_code || customer.store_name || '-'"></span>
                        </td>

                        <!-- Customer Number -->
                        <td class="px-4 py-3 text-sm">
                            <span class="font-mono text-xs" x-text="customer.customer_number"></span>
                        </td>

                        <!-- Status -->
                        <td class="px-4 py-3 text-xs">
                            <span
                                class="px-2 py-1 font-semibold leading-tight rounded-full"
                                :class="customer.is_active
                                    ? 'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100'
                                    : 'text-red-700 bg-red-100 dark:bg-red-700 dark:text-red-100'"
                                x-text="customer.is_active ? 'Active' : 'Inactive'"
                            ></span>
                        </td>

                        <!-- Joined -->
                        <td class="px-4 py-3 text-sm">
                            <span x-text="formatDate(customer.created_at)"></span>
                        </td>

                        <!-- Actions -->
                        <td class="px-4 py-3">
                            <div class="flex items-center space-x-2 text-sm">
                                <button
                                    @click="pendingToggleCustomer = customer; showToggleStatusConfirm = true"
                                    class="px-2 py-1 text-xs font-medium leading-5 rounded-lg"
                                    :class="customer.is_active
                                        ? 'text-red-600 hover:bg-red-100 dark:text-red-400 dark:hover:bg-red-700/50'
                                        : 'text-green-600 hover:bg-green-100 dark:text-green-400 dark:hover:bg-green-700/50'"
                                    :title="customer.is_active ? 'Deactivate' : 'Activate'"
                                >
                                    <span x-html="customer.is_active ? $icon('x-circle', 'w-4 h-4') : $icon('check-circle', 'w-4 h-4')"></span>
                                </button>
                            </div>
                        </td>
                    </tr>
                </template>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    {{ pagination() }}
</div>

<!-- Toggle Customer Status Confirm Modal -->
{{ confirm_modal_dynamic('toggleStatusConfirm', 'Change Customer Status', "'Are you sure you want to ' + (pendingToggleCustomer?.is_active ? 'deactivate' : 'activate') + ' this customer?'", 'toggleStatus(pendingToggleCustomer)', 'showToggleStatusConfirm', 'Confirm', 'Cancel', 'warning') }}
{% endblock %}

{% block extra_scripts %}
<!-- Tom Select JS with local fallback -->
<script>
(function() {
    var script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/tom-select@2.4.1/dist/js/tom-select.complete.min.js';
    script.onerror = function() {
        console.warn('Tom Select CDN failed, loading local copy...');
        var fallbackScript = document.createElement('script');
        fallbackScript.src = '{{ url_for("static", path="shared/js/lib/tom-select.complete.min.js") }}';
        document.head.appendChild(fallbackScript);
    };
    document.head.appendChild(script);
})();
</script>
<script defer src="{{ url_for('customers_static', path='admin/js/customers.js') }}"></script>
{% endblock %}
