<x-layouts.app title="Usuários" subtitle="Todos os acessos, de todas as empresas">
    <div class="grid gap-6 lg:grid-cols-3">
        <div class="lg:col-span-2 space-y-4">
            {{-- Filtros --}}
            <form method="GET" action="{{ route('master.usuarios') }}" class="card card-pad">
                <div class="grid gap-4 sm:grid-cols-[1fr_auto_auto]">
                    <div>
                        <label for="q" class="label">Buscar</label>
                        <input id="q" name="q" type="search" value="{{ $busca }}"
                               placeholder="Nome ou e-mail" class="input">
                    </div>

                    <div>
                        <label for="empresa" class="label">Empresa</label>
                        <select id="empresa" name="empresa" class="input">
                            <option value="">Todas</option>
                            @foreach ($empresas as $empresa)
                                <option value="{{ $empresa->id }}" @selected((string) $empresaId === (string) $empresa->id)>
                                    {{ $empresa->razao_social }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div class="flex items-end gap-2">
                        <button class="btn-primary">Filtrar</button>
                        @if ($busca || $empresaId)
                            <a href="{{ route('master.usuarios') }}" class="btn-secondary">Limpar</a>
                        @endif
                    </div>
                </div>
            </form>

            {{-- Lista --}}
            <div class="card overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-slate-200">
                        <thead class="bg-slate-50">
                            <tr>
                                <th class="th">Usuário</th>
                                <th class="th">Empresa</th>
                                <th class="th">Perfil</th>
                                <th class="th">Último acesso</th>
                                <th class="th sr-only">Ações</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 bg-white">
                            @forelse ($usuarios as $usuario)
                                <tr x-data="{ editando: false }" class="align-top">
                                    <td class="td">
                                        <p class="font-medium text-slate-900">{{ $usuario->name }}</p>
                                        <p class="text-xs text-slate-500">{{ $usuario->email }}</p>
                                        @unless ($usuario->is_active)
                                            <span class="badge mt-1 bg-slate-100 text-slate-600">inativo</span>
                                        @endunless
                                    </td>

                                    <td class="td">
                                        @if ($usuario->company)
                                            <a href="{{ route('master.empresas.show', $usuario->company_id) }}"
                                               class="text-brand-700 hover:text-brand-800">
                                                {{ Str::limit($usuario->company->razao_social, 26) }}
                                            </a>
                                        @else
                                            <span class="text-slate-400">plataforma</span>
                                        @endif
                                    </td>

                                    <td class="td">{{ $usuario->roleLabel() }}</td>

                                    <td class="td tabular whitespace-nowrap">
                                        {{ $usuario->last_login_at?->format('d/m/Y H:i') ?: '—' }}
                                    </td>

                                    <td class="td text-right whitespace-nowrap">
                                        @if ($usuario->isMaster())
                                            <span class="text-xs text-slate-400">conta da plataforma</span>
                                        @else
                                            <button type="button" @click="editando = !editando" class="btn-secondary btn-sm">Editar</button>

                                            <div x-show="editando" x-cloak class="mt-3 w-72 rounded-lg bg-slate-50 p-4 text-left">
                                                <form method="POST" action="{{ route('master.usuarios.update', $usuario) }}" class="space-y-3">
                                                    @csrf @method('PUT')

                                                    <div>
                                                        <label class="label">Nome</label>
                                                        <input name="name" value="{{ $usuario->name }}" required class="input">
                                                    </div>

                                                    <div>
                                                        <label class="label">Perfil</label>
                                                        <select name="role" class="input">
                                                            <option value="admin" @selected($usuario->role === 'admin')>Administrador</option>
                                                            <option value="user" @selected($usuario->role === 'user')>Operador</option>
                                                        </select>
                                                    </div>

                                                    <div>
                                                        <label class="label">Nova senha <span class="font-normal text-slate-400">(opcional)</span></label>
                                                        <input name="password" type="password" autocomplete="new-password" class="input">
                                                    </div>

                                                    <label class="flex cursor-pointer items-center gap-2 text-sm text-slate-600">
                                                        <input type="checkbox" name="is_active" value="1" @checked($usuario->is_active)
                                                               class="size-4 cursor-pointer rounded border-slate-300 text-brand-700 focus:ring-brand-500">
                                                        Acesso ativo
                                                    </label>

                                                    <div class="flex gap-2">
                                                        <button class="btn-primary btn-sm">Salvar</button>
                                                        <button type="button" @click="editando = false" class="btn-secondary btn-sm">Cancelar</button>
                                                    </div>
                                                </form>

                                                <form method="POST" action="{{ route('master.usuarios.destroy', $usuario) }}"
                                                      class="mt-3 border-t border-slate-200 pt-3"
                                                      onsubmit="return confirm('Remover o acesso de {{ $usuario->name }}?')">
                                                    @csrf @method('DELETE')
                                                    <button class="btn-danger btn-sm w-full">Remover usuário</button>
                                                </form>
                                            </div>
                                        @endif
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="5" class="px-4 py-16 text-center text-sm text-slate-500">
                                        Nenhum usuário encontrado.
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                @if ($usuarios->hasPages())
                    <div class="border-t border-slate-100 px-4 py-3">{{ $usuarios->links() }}</div>
                @endif
            </div>
        </div>

        {{-- Novo usuário --}}
        <div class="card card-pad h-fit">
            <h2 class="text-sm font-semibold text-slate-900">Novo usuário</h2>
            <p class="mt-1 text-sm text-slate-500">Cria o acesso já vinculado à empresa escolhida.</p>

            <form method="POST" action="{{ route('master.usuarios.store') }}" class="mt-5 space-y-4">
                @csrf

                <div>
                    <label for="novo_empresa" class="label">Empresa</label>
                    <select id="novo_empresa" name="company_id" required class="input">
                        <option value="">Selecione</option>
                        @foreach ($empresas as $empresa)
                            <option value="{{ $empresa->id }}" @selected(old('company_id') == $empresa->id)>
                                {{ $empresa->razao_social }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <div>
                    <label for="novo_nome" class="label">Nome</label>
                    <input id="novo_nome" name="name" value="{{ old('name') }}" required class="input">
                </div>

                <div>
                    <label for="novo_email" class="label">E-mail</label>
                    <input id="novo_email" name="email" type="email" value="{{ old('email') }}" required class="input">
                </div>

                <div>
                    <label for="novo_perfil" class="label">Perfil</label>
                    <select id="novo_perfil" name="role" class="input">
                        <option value="user">Operador — consulta e baixa XMLs</option>
                        <option value="admin">Administrador — também configura o monitor</option>
                    </select>
                </div>

                <div>
                    <label for="nova_senha" class="label">Senha</label>
                    <input id="nova_senha" name="password" type="password" required autocomplete="new-password" class="input">
                </div>

                <button class="btn-primary w-full">Criar usuário</button>
            </form>
        </div>
    </div>
</x-layouts.app>
