<x-app-layout>

    <x-module-hero title="User Management" description="Manage all users, roles, and account statuses" icon="fa-users">
        <x-slot name="tabs">
            @can('view users')
                <a href="{{ route('users.index') }}"
                   class="module-hero-tab {{ request()->routeIs('users.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                          inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                          md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                    <i class="fas fa-list text-sm"></i> All Users
                </a>
            @endcan
            @can('create users')
                <a href="{{ route('users.create') }}"
                   class="module-hero-tab {{ request()->routeIs('users.create') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                          inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                          md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                    <i class="fas fa-user-plus text-sm"></i> New User
                </a>
            @endcan
            @hasRole('Super Manager')
                @if(Route::has('roles.index'))
                    <a href="{{ route('roles.index') }}"
                       class="module-hero-tab {{ request()->routeIs('roles.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                              inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                              md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                        <i class="fas fa-user-tag text-sm"></i> Roles
                    </a>
                @endif
                @if(Route::has('roles.assign'))
                    <a href="{{ route('roles.assign') }}"
                       class="module-hero-tab {{ request()->routeIs('roles.assign') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                              inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                              md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                        <i class="fas fa-key text-sm"></i> Assign Permissions
                    </a>
                @endif
                @if(Route::has('admin.themes.index'))
                    <a href="{{ route('admin.themes.index') }}"
                       class="module-hero-tab {{ request()->routeIs('admin.themes.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                              inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                              md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                        <i class="fas fa-palette text-sm"></i> Themes
                    </a>
                @endif
            @endhasRole
        </x-slot>
        <x-slot name="actions">
            @can('create users')
                <a href="{{ route('users.create') }}" class="inline-flex items-center gap-2 px-4 py-2 bg-white text-[#1e293b] rounded-lg hover:bg-gray-100 transition font-medium text-sm shadow">
                    <i class="fas fa-user-plus"></i> Create New User
                </a>
            @endcan
            <button onclick="window.print()" class="inline-flex items-center gap-2 px-4 py-2 bg-[#e2e8f0] text-[#1e293b] border border-[#cbd5e1] rounded-lg hover:bg-[#cbd5e1] transition font-medium text-sm">
                <i class="fas fa-print"></i> Print List
            </button>
        </x-slot>
    </x-module-hero>

    <div class="p-6">

        {{-- Flash Messages --}}
        @if(session('success'))
            <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center gap-2">
                <i class="fas fa-check-circle"></i> {{ session('success') }}
            </div>
        @endif
        @if(session('error'))
            <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center gap-2">
                <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
            </div>
        @endif

        <div class="bg-white rounded-lg shadow-sm overflow-hidden">

            {{-- Search & Filter Bar --}}
            <div class="p-4 border-b border-gray-200" x-data="{
                showFilters: false,
                isSearching: false,
                submitForm() { this.isSearching = true; this.$refs.searchForm.submit(); }
            }">
                <form x-ref="searchForm" method="GET" action="{{ route('users.index') }}" class="space-y-3">
                    <div class="flex flex-col sm:flex-row gap-3">
                        <div class="flex-1 relative">
                            <input type="text" name="search" value="{{ request('search') }}"
                                placeholder="Search by name, email, or role..."
                                class="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" />
                            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                        </div>
                        <div class="flex gap-2">
                            <button type="button" @click="showFilters = !showFilters"
                                class="px-4 py-2.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm font-medium border border-gray-300">
                                <i class="fas fa-filter mr-1"></i> Filters
                                <i class="fas fa-chevron-down ml-1 transition-transform" :class="{'rotate-180': showFilters}"></i>
                            </button>
                            <button type="button" @click="submitForm()" :disabled="isSearching"
                                class="px-5 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition text-sm font-medium disabled:opacity-50">
                                <i x-show="!isSearching" class="fas fa-search mr-1"></i>
                                <i x-show="isSearching" class="fas fa-spinner fa-spin mr-1"></i>
                                <span x-text="isSearching ? 'Searching...' : 'Search'"></span>
                            </button>
                        </div>
                    </div>

                    <div x-show="showFilters"
                         x-transition:enter="transition ease-out duration-200"
                         x-transition:enter-start="opacity-0 -translate-y-1"
                         x-transition:enter-end="opacity-100 translate-y-0"
                         class="grid grid-cols-1 md:grid-cols-3 gap-3 p-4 bg-gray-50 rounded-lg border border-gray-200">
                        <div>
                            <label class="block text-xs font-medium text-gray-600 mb-1">Filter by Role</label>
                            <select name="role" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500">
                                <option value="">All Roles</option>
                                @foreach($roles as $role)
                                    <option value="{{ $role->id }}" {{ request('role') == $role->id ? 'selected' : '' }}>{{ $role->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-gray-600 mb-1">Filter by Status</label>
                            <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500">
                                <option value="">All Statuses</option>
                                <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>Active</option>
                                <option value="inactive" {{ request('status') == 'inactive' ? 'selected' : '' }}>Inactive</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-gray-600 mb-1">Results Per Page</label>
                            <select name="per_page" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500">
                                <option value="15" {{ request('per_page', 15) == 15 ? 'selected' : '' }}>15</option>
                                <option value="25" {{ request('per_page') == 25 ? 'selected' : '' }}>25</option>
                                <option value="50" {{ request('per_page') == 50 ? 'selected' : '' }}>50</option>
                                <option value="100" {{ request('per_page') == 100 ? 'selected' : '' }}>100</option>
                            </select>
                        </div>
                        <div class="md:col-span-3 flex justify-end">
                            <a href="{{ route('users.index') }}" class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition text-sm font-medium">
                                <i class="fas fa-times mr-1"></i> Clear Filters
                            </a>
                        </div>
                    </div>
                </form>
            </div>

            {{-- Desktop Table --}}
            <div class="hidden md:block overflow-x-auto">
                <table class="w-full table-zebra">
                    <thead>
                        <tr>
                            <th class="th-col-1 px-4 py-3 text-left">User</th>
                            <th class="th-col-2 px-4 py-3 text-left">Roles</th>
                            <th class="th-col-3 px-4 py-3 text-left">Status</th>
                            <th class="th-col-4 px-4 py-3 text-left">Joined</th>
                            <th class="th-col-5 px-4 py-3 text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($users as $user)
                            <tr x-data="{
                                isActive: {{ $user->is_active ? 'true' : 'false' }},
                                isLoading: false,
                                toggleActive() {
                                    if (!confirm('Are you sure you want to ' + (this.isActive ? 'deactivate' : 'activate') + ' this user?')) return;
                                    this.isLoading = true;
                                    fetch('{{ route('users.toggleActive', $user) }}', {
                                        method: 'PATCH',
                                        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json', 'Content-Type': 'application/json' }
                                    })
                                    .then(r => r.json())
                                    .then(data => {
                                        this.isLoading = false;
                                        if (data.success) { this.isActive = data.is_active; window.showToast(data.message, 'success'); }
                                        else { window.showToast(data.message || 'An error occurred', 'error'); }
                                    })
                                    .catch(() => { this.isLoading = false; window.showToast('An error occurred.', 'error'); });
                                }
                            }" class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                <td class="px-4 py-3">
                                    <div class="flex items-center gap-3">
                                        <div class="w-9 h-9 rounded-full bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center text-white text-xs font-bold flex-shrink-0">
                                            {{ strtoupper(substr($user->name, 0, 2)) }}
                                        </div>
                                        <div>
                                            <div class="text-sm font-medium text-gray-900">{{ $user->name }}</div>
                                            <div class="text-xs text-gray-500">{{ $user->email }}</div>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex flex-wrap gap-1">
                                        @forelse($user->roles as $role)
                                            <span class="inline-flex items-center px-2 py-0.5 text-xs font-semibold text-purple-800 bg-purple-100 rounded-full">{{ $role->name }}</span>
                                        @empty
                                            <span class="text-xs text-gray-400">No roles</span>
                                        @endforelse
                                    </div>
                                </td>
                                <td class="px-4 py-3">
                                    <span x-show="isActive" class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-semibold text-green-800 bg-green-100 rounded-full">
                                        <i class="fas fa-check-circle"></i> Active
                                    </span>
                                    <span x-show="!isActive" class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-semibold text-red-800 bg-red-100 rounded-full">
                                        <i class="fas fa-times-circle"></i> Inactive
                                    </span>
                                </td>
                                <td class="px-4 py-3 text-sm text-gray-500 whitespace-nowrap">
                                    {{ $user->created_at->format('M d, Y') }}
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex items-center justify-center gap-1.5">
                                        @can('view users')
                                            <a href="{{ route('users.show', $user) }}" class="btn-action-view">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                        @endcan
                                        @can('edit users')
                                            <a href="{{ route('users.edit', $user) }}" class="btn-action-edit">
                                                <i class="fas fa-edit"></i> Edit
                                            </a>
                                        @endcan
                                        @can('manage users')
                                            @if($user->id !== auth()->id())
                                                <button @click="toggleActive()" :disabled="isLoading"
                                                    class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-white rounded bg-orange-500 hover:bg-orange-600 transition disabled:opacity-50">
                                                    <i x-show="!isLoading" class="fas fa-toggle-on"></i>
                                                    <i x-show="isLoading" class="fas fa-spinner fa-spin"></i>
                                                    Toggle
                                                </button>
                                            @endif
                                        @endcan
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                <td colspan="5" class="px-4 py-12 text-center">
                                    <div class="flex flex-col items-center text-gray-400">
                                        <i class="fas fa-users text-5xl mb-3"></i>
                                        <p class="font-medium text-gray-500">No users found</p>
                                        <p class="text-sm">Try adjusting your search or filter criteria</p>
                                    </div>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            {{-- Mobile Cards --}}
            <div class="md:hidden divide-y divide-gray-200">
                @forelse($users as $user)
                    <div class="p-4" x-data="{
                        isActive: {{ $user->is_active ? 'true' : 'false' }},
                        isLoading: false,
                        toggleActive() {
                            if (!confirm('Are you sure you want to ' + (this.isActive ? 'deactivate' : 'activate') + ' this user?')) return;
                            this.isLoading = true;
                            fetch('{{ route('users.toggleActive', $user) }}', {
                                method: 'PATCH',
                                headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json', 'Content-Type': 'application/json' }
                            })
                            .then(r => r.json())
                            .then(data => {
                                this.isLoading = false;
                                if (data.success) { this.isActive = data.is_active; window.showToast(data.message, 'success'); }
                                else { window.showToast(data.message || 'An error occurred', 'error'); }
                            })
                            .catch(() => { this.isLoading = false; window.showToast('An error occurred.', 'error'); });
                        }
                    }">
                        <div class="flex items-center justify-between mb-3">
                            <div class="flex items-center gap-3">
                                <div class="w-11 h-11 rounded-full bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center text-white font-bold">
                                    {{ strtoupper(substr($user->name, 0, 2)) }}
                                </div>
                                <div>
                                    <div class="font-medium text-gray-900 text-sm">{{ $user->name }}</div>
                                    <div class="text-xs text-gray-500">{{ $user->email }}</div>
                                </div>
                            </div>
                            <span x-show="isActive" class="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-semibold text-green-800 bg-green-100 rounded-full">
                                <i class="fas fa-check-circle"></i> Active
                            </span>
                            <span x-show="!isActive" class="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-semibold text-red-800 bg-red-100 rounded-full">
                                <i class="fas fa-times-circle"></i> Inactive
                            </span>
                        </div>
                        <div class="flex flex-wrap gap-1 mb-3">
                            @forelse($user->roles as $role)
                                <span class="inline-flex items-center px-2 py-0.5 text-xs font-semibold text-purple-800 bg-purple-100 rounded-full">{{ $role->name }}</span>
                            @empty
                                <span class="text-xs text-gray-400">No roles</span>
                            @endforelse
                        </div>
                        <div class="text-xs text-gray-500 mb-3">Joined {{ $user->created_at->format('M d, Y') }}</div>
                        <div class="flex gap-2 pt-2 border-t border-gray-100">
                            @can('view users')
                                <a href="{{ route('users.show', $user) }}" class="btn-action-view flex-1 justify-center">
                                    <i class="fas fa-eye"></i> View
                                </a>
                            @endcan
                            @can('edit users')
                                <a href="{{ route('users.edit', $user) }}" class="btn-action-edit flex-1 justify-center">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                            @endcan
                            @can('manage users')
                                @if($user->id !== auth()->id())
                                    <button @click="toggleActive()" :disabled="isLoading"
                                        class="flex-1 inline-flex items-center justify-center gap-1 px-3 py-1.5 text-xs font-medium text-white rounded bg-orange-500 hover:bg-orange-600 transition disabled:opacity-50">
                                        <i x-show="!isLoading" class="fas fa-toggle-on"></i>
                                        <i x-show="isLoading" class="fas fa-spinner fa-spin"></i>
                                        Toggle
                                    </button>
                                @endif
                            @endcan
                        </div>
                    </div>
                @empty
                    <div class="p-12 text-center">
                        <div class="flex flex-col items-center text-gray-400">
                            <i class="fas fa-users text-5xl mb-3"></i>
                            <p class="font-medium text-gray-500">No users found</p>
                        </div>
                    </div>
                @endforelse
            </div>

            {{-- Pagination --}}
            @if($users->hasPages())
                <div class="px-4 py-3 border-t border-gray-200">
                    {{ $users->links() }}
                </div>
            @endif

        </div>
    </div>

</x-app-layout>
