<div class="space-y-5">
    <section class="rounded-lg border border-slate-200 bg-white p-5 shadow-soft dark:border-slate-800 dark:bg-slate-900">
        <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
            <div>
                <p class="text-xs font-semibold uppercase tracking-wide text-primary-600 dark:text-primary-300">Administracao</p>
                <h1 class="mt-1 text-2xl font-bold text-slate-950 dark:text-white">Usuarios</h1>
                <p class="mt-2 text-sm leading-6 text-slate-600 dark:text-slate-400">Cadastre usuarios, vincule departamentos, defina papeis e libere os modulos permitidos.</p>
            </div>

            <button type="button" wire:click="abrirCriacao" class="btn-primary">
                <x-heroicon name="user-plus" class="h-5 w-5" />
                Novo usuario
            </button>
        </div>

        <div class="mt-5">
            <label class="relative block max-w-xl">
                <x-heroicon name="magnifying-glass" class="pointer-events-none absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
                <input wire:model.debounce.350ms="busca" type="search" class="form-control pl-10" placeholder="Buscar por nome ou e-mail...">
            </label>
        </div>
    </section>

    <section class="overflow-hidden rounded-lg border border-slate-200 bg-white shadow-soft dark:border-slate-800 dark:bg-slate-900">
        <div class="hidden grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)_160px_150px_220px] gap-4 border-b border-slate-200 px-4 py-3 text-xs font-bold uppercase tracking-wide text-slate-500 dark:border-slate-800 dark:text-slate-400 xl:grid">
            <span>Usuario</span>
            <span>Departamento</span>
            <span>Papel</span>
            <span>Status</span>
            <span class="text-right">Acoes</span>
        </div>

        <div class="divide-y divide-slate-200 dark:divide-slate-800">
            @forelse ($usuarios as $usuario)
                @php
                    $modulosPermitidos = collect($modulos)->filter(fn ($modulo) => $usuario->can($modulo['permissao']));
                @endphp

                <article class="grid gap-4 p-4 xl:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)_160px_150px_220px] xl:items-center">
                    <div class="min-w-0">
                        <div class="flex items-center gap-3">
                            <x-user-avatar :user="$usuario" size="md" />
                            <div class="min-w-0">
                                <h2 class="truncate text-sm font-bold text-slate-950 dark:text-white">{{ $usuario->name }}</h2>
                                <p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ $usuario->email }}</p>
                            </div>
                        </div>

                        <div class="mt-3 flex flex-wrap gap-1.5 xl:hidden">
                            @foreach ($modulosPermitidos->take(4) as $modulo)
                                <x-badge>{{ $modulo['nome'] }}</x-badge>
                            @endforeach
                            @if ($modulosPermitidos->count() > 4)
                                <x-badge>+{{ $modulosPermitidos->count() - 4 }}</x-badge>
                            @endif
                        </div>
                    </div>

                    <div class="text-sm text-slate-600 dark:text-slate-300">
                        {{ $usuario->departamento->nome ?? 'Sem departamento' }}
                    </div>

                    <div>
                        <x-badge variant="primary">{{ $usuario->roles->first()?->name ?? 'Sem papel' }}</x-badge>
                    </div>

                    <div>
                        <x-badge :variant="$usuario->ativo ? 'success' : 'warning'">{{ $usuario->ativo ? 'Ativo' : 'Inativo' }}</x-badge>
                    </div>

                    <div class="flex flex-wrap justify-start gap-2 xl:justify-end">
                        <button type="button" wire:click="editar({{ $usuario->id }})" class="btn-secondary px-3 py-1.5">
                            Editar
                        </button>

                        @if ($usuario->id !== auth()->id())
                            <button type="button" wire:click="alternarAtivo({{ $usuario->id }})" class="btn-secondary px-3 py-1.5">
                                {{ $usuario->ativo ? 'Inativar' : 'Ativar' }}
                            </button>

                            <button type="button"
                                    x-data
                                    x-on:click="if (confirm('Excluir este usuario? Esta acao nao remove artigos ja criados, mas remove o acesso.')) { $wire.excluir({{ $usuario->id }}) }"
                                    class="inline-flex items-center justify-center rounded-lg border border-rose-300 bg-white px-3 py-1.5 text-sm font-semibold text-rose-700 transition hover:bg-rose-50 dark:border-rose-800 dark:bg-slate-950 dark:text-rose-300 dark:hover:bg-rose-950/30">
                                Excluir
                            </button>
                        @endif
                    </div>
                </article>
            @empty
                <div class="p-10 text-center">
                    <h2 class="text-lg font-bold text-slate-950 dark:text-white">Nenhum usuario encontrado</h2>
                    <p class="mt-2 text-sm text-slate-600 dark:text-slate-400">Crie o primeiro usuario ou ajuste a busca.</p>
                </div>
            @endforelse
        </div>

        <div class="border-t border-slate-200 p-4 dark:border-slate-800">
            {{ $usuarios->links() }}
        </div>
    </section>

    @if ($modalAberto)
        <div class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/70 p-4 backdrop-blur-sm">
            <div class="max-h-[92vh] w-full max-w-5xl overflow-y-auto rounded-lg border border-slate-200 bg-white p-6 shadow-2xl dark:border-slate-800 dark:bg-slate-900">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h2 class="text-xl font-bold text-slate-950 dark:text-white">{{ $usuarioEditandoId ? 'Editar usuario' : 'Novo usuario' }}</h2>
                        <p class="mt-1 text-sm text-slate-600 dark:text-slate-400">As permissoes de modulo controlam o que aparece no portal e o que pode ser acessado.</p>
                    </div>
                    <button type="button" wire:click="$set('modalAberto', false)" class="rounded-lg p-2 text-slate-500 transition hover:bg-slate-100 dark:hover:bg-slate-800">Fechar</button>
                </div>

                <form wire:submit.prevent="salvar" class="mt-6 space-y-5">
                    <div class="flex flex-col gap-4 rounded-lg border border-slate-200 p-4 dark:border-slate-800 sm:flex-row sm:items-center">
                        @if ($fotoPerfil)
                            <img src="{{ $fotoPerfil->temporaryUrl() }}" alt="Previa da foto" class="h-14 w-14 shrink-0 rounded-lg object-cover ring-1 ring-slate-200 dark:ring-slate-700">
                        @elseif ($usuarioEditandoId)
                            <x-user-avatar :user="\App\Models\User::find($usuarioEditandoId)" size="lg" />
                        @else
                            <span class="flex h-14 w-14 shrink-0 items-center justify-center rounded-lg bg-accent-100 font-bold text-accent-700 ring-1 ring-slate-200 dark:bg-slate-800 dark:text-accent-300 dark:ring-slate-700">
                                U
                            </span>
                        @endif

                        <div class="min-w-0 flex-1">
                            <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Foto de perfil</label>
                            <input wire:model="fotoPerfil" type="file" accept="image/*" class="form-control">
                            <p class="mt-2 text-xs text-slate-500 dark:text-slate-400">A foto aparece no perfil, menu lateral e autoria dos artigos da Wiki.</p>
                            <x-input-error :messages="$errors->get('fotoPerfil')" />
                        </div>
                    </div>

                    <div class="grid gap-4 md:grid-cols-2">
                        <div>
                            <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Nome</label>
                            <input wire:model.defer="name" type="text" class="form-control">
                            <x-input-error :messages="$errors->get('name')" />
                        </div>

                        <div>
                            <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">E-mail</label>
                            <input wire:model.defer="email" type="email" class="form-control">
                            <x-input-error :messages="$errors->get('email')" />
                        </div>

                        <div>
                            <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Senha {{ $usuarioEditandoId ? '(preencha apenas para alterar)' : '' }}</label>
                            <input wire:model.defer="password" type="password" class="form-control" autocomplete="new-password">
                            <x-input-error :messages="$errors->get('password')" />
                        </div>

                        <div>
                            <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Departamento</label>
                            <select wire:model.defer="departamento_id" class="form-control">
                                <option value="">Sem departamento</option>
                                @foreach ($departamentos as $departamento)
                                    <option value="{{ $departamento->id }}">{{ $departamento->nome }}</option>
                                @endforeach
                            </select>
                            <x-input-error :messages="$errors->get('departamento_id')" />
                        </div>

                        <div>
                            <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Papel</label>
                            <select wire:model.defer="papel" class="form-control">
                                @foreach ($papeis as $papelItem)
                                    <option value="{{ $papelItem }}">{{ $papelItem }}</option>
                                @endforeach
                            </select>
                            <x-input-error :messages="$errors->get('papel')" />
                        </div>

                        <label class="flex items-center gap-3 rounded-lg border border-slate-200 px-4 py-3 text-sm font-semibold text-slate-700 dark:border-slate-800 dark:text-slate-200">
                            <input wire:model.defer="ativo" type="checkbox" class="rounded border-slate-300 text-primary-600 focus:ring-primary-500">
                            Usuario ativo
                        </label>
                    </div>

                    <section class="rounded-lg border border-slate-200 p-4 dark:border-slate-800">
                        <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
                            <div>
                                <h3 class="text-sm font-bold text-slate-950 dark:text-white">Acesso aos modulos</h3>
                                <p class="mt-1 text-xs leading-5 text-slate-500 dark:text-slate-400">Administrador Master e Diretoria recebem todos os modulos pelo papel. Para os demais, marque os modulos liberados para aparecer no portal.</p>
                            </div>
                            <span class="text-xs font-semibold text-slate-500 dark:text-slate-400">{{ count($modulosSelecionados) }} selecionados</span>
                        </div>

                        <div class="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
                            @foreach ($modulos as $modulo)
                                <label class="flex cursor-pointer items-start gap-3 rounded-lg border border-slate-200 p-3 transition hover:border-primary-300 hover:bg-primary-50/50 dark:border-slate-800 dark:hover:border-primary-700 dark:hover:bg-primary-950/20">
                                    <input wire:model.defer="modulosSelecionados" type="checkbox" value="{{ $modulo['permissao'] }}" class="mt-1 rounded border-slate-300 text-primary-600 focus:ring-primary-500">
                                    <span class="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-accent-50 text-accent-700 dark:bg-slate-800 dark:text-accent-300">
                                        <x-heroicon :name="$modulo['icone']" class="h-5 w-5" />
                                    </span>
                                    <span class="min-w-0">
                                        <span class="block text-sm font-bold text-slate-950 dark:text-white">{{ $modulo['nome'] }}</span>
                                        <span class="mt-1 line-clamp-2 block text-xs leading-5 text-slate-500 dark:text-slate-400">{{ $modulo['descricao'] }}</span>
                                    </span>
                                </label>
                            @endforeach
                        </div>

                        <x-input-error :messages="$errors->get('modulosSelecionados')" />
                        <x-input-error :messages="$errors->get('modulosSelecionados.*')" />
                    </section>

                    <div class="flex justify-end gap-3 border-t border-slate-200 pt-5 dark:border-slate-800">
                        <button type="button" wire:click="$set('modalAberto', false)" class="btn-secondary">Cancelar</button>
                        <button type="submit" class="btn-primary">Salvar usuario</button>
                    </div>
                </form>
            </div>
        </div>
    @endif
</div>
