<x-app-layout>
    <x-slot name="title">
        Gestión de Usuarios
    </x-slot>

    <!-- Barra de Herramientas y Filtros -->
    <div class="card mb-4 border-0 shadow-sm rounded-4">
        <div class="card-body p-4">
            <div class="row g-3 align-items-center justify-content-between">
                <div class="col-md-9">
                    <form method="GET" action="{{ route('admin.usuarios.index') }}" class="d-flex flex-wrap gap-2">
                        <div class="input-group" style="max-width: 300px;">
                            <span class="input-group-text bg-light border-end-0"><i class="bi bi-search text-muted"></i></span>
                            <input type="text" name="search" value="{{ request('search') }}" placeholder="Buscar por nombre o email..." class="form-control border-start-0 ps-0">
                        </div>

                        <select name="rol" class="form-select tom-select" style="max-width: 200px;">
                            <option value="">Cualquier Rol</option>
                            @foreach($roles as $r)
                                <option value="{{ $r }}" {{ request('rol') == $r ? 'selected' : '' }}>{{ ucfirst($r) }}</option>
                            @endforeach
                        </select>

                        <select name="activo" class="form-select tom-select" style="max-width: 150px;">
                            <option value="">Estado</option>
                            <option value="1" {{ request('activo') === '1' ? 'selected' : '' }}>Activos</option>
                            <option value="0" {{ request('activo') === '0' ? 'selected' : '' }}>Inactivos</option>
                        </select>

                        <button type="submit" class="btn btn-outline-secondary rounded-pill fw-bold px-4">
                            Filtrar
                        </button>
                        
                        @if(request()->hasAny(['search', 'rol', 'activo']))
                            <a href="{{ route('admin.usuarios.index') }}" class="btn btn-light rounded-pill border px-3">Limpiar</a>
                        @endif
                    </form>
                </div>
                <div class="col-md-3 text-md-end mt-3 mt-md-0">
                    <button type="button" class="btn btn-primary rounded-pill fw-bold shadow-sm w-100 w-md-auto" data-bs-toggle="modal" data-bs-target="#createUserModal">
                        <i class="bi bi-person-plus-fill me-1"></i> Nuevo Usuario
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabla -->
    <div class="card border-0 shadow-sm rounded-4">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4 py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Usuario</th>
                            <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Rol</th>
                            <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Sucursales Asignadas</th>
                            <th class="py-3 text-center text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Estado</th>
                            <th class="pe-4 py-3 text-end text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Acciones</th>
                        </tr>
                    </thead>
                    <tbody class="border-top-0">
                        @forelse($usuarios as $usr)
                            <tr>
                                <td class="ps-4 py-3">
                                    <div class="d-flex align-items-center">
                                        <div class="rounded-circle d-flex align-items-center justify-content-center text-white fw-bold me-3 text-uppercase shadow-sm" style="width: 42px; height: 42px; background: linear-gradient(135deg, #a855f7, #6366f1); font-size: 0.9rem;">
                                            {{ substr($usr->name, 0, 2) }}
                                        </div>
                                        <div>
                                            <div class="fw-bold text-dark">{{ $usr->name }}</div>
                                            <div class="text-muted small">{{ $usr->email }}</div>
                                            @if($usr->dni)
                                                <div class="text-muted" style="font-size: 0.65rem;">DNI: {{ $usr->dni }}</div>
                                            @endif
                                        </div>
                                    </div>
                                </td>
                                <td class="py-3">
                                    @php $rolName = $usr->getRoleNames()->first() ?? 'Sin Rol'; @endphp
                                    <span class="badge rounded-pill px-3 py-2
                                        @if($rolName == 'admin') bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25
                                        @elseif($rolName == 'chef') bg-warning bg-opacity-10 text-warning border border-warning border-opacity-25 text-dark
                                        @elseif($rolName == 'cajero') bg-success bg-opacity-10 text-success border border-success border-opacity-25
                                        @else bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 @endif
                                    ">
                                        {{ ucfirst($rolName) }}
                                    </span>
                                </td>
                                <td class="py-3">
                                    <div class="d-flex flex-wrap gap-1">
                                        @foreach($usr->sucursales->take(3) as $s)
                                            <span class="badge bg-light text-dark border fw-normal">{{ $s->nombre }}</span>
                                        @endforeach
                                        @if($usr->sucursales->count() > 3)
                                            <span class="badge bg-light text-muted border fw-normal">+{{ $usr->sucursales->count() - 3 }}</span>
                                        @endif
                                        @if($usr->sucursales->isEmpty())
                                            <span class="text-muted small fst-italic">Ninguna</span>
                                        @endif
                                    </div>
                                </td>
                                <td class="py-3 text-center">
                                    @if($usr->activo)
                                        <span class="badge bg-success bg-opacity-10 text-success rounded-pill px-3"><i class="bi bi-circle-fill me-1" style="font-size: 0.5rem;"></i> Activo</span>
                                    @else
                                        <span class="badge bg-secondary bg-opacity-10 text-secondary rounded-pill px-3"><i class="bi bi-circle-fill me-1" style="font-size: 0.5rem;"></i> Inactivo</span>
                                    @endif
                                </td>
                                <td class="pe-4 py-3 text-end">
                                    <div class="d-flex justify-content-end gap-2">
                                        <!-- Botón Editar -->
                                        <a href="{{ route('admin.usuarios.edit', $usr) }}" class="btn btn-sm btn-light border rounded-circle" title="Editar usuario">
                                            <i class="bi bi-pencil-square text-primary"></i>
                                        </a>
                                        
                                        <!-- Form Toggle Activo -->
                                        @if($usr->id !== auth()->id())
                                            <form action="{{ route('admin.usuarios.toggle', $usr) }}" method="POST" class="d-inline">
                                                @csrf
                                                @method('PATCH')
                                                <button type="submit" class="btn btn-sm {{ $usr->activo ? 'btn-light border disabled-hover' : 'btn-success' }} rounded-circle" title="{{ $usr->activo ? 'Desactivar usuario' : 'Activar usuario' }}" onclick="event.preventDefault(); confirmAction(this, '¿Seguro de cambiar el estado de este usuario?')">
                                                    <i class="bi bi-power {{ $usr->activo ? 'text-danger' : 'text-white' }}"></i>
                                                </button>
                                            </form>
                                        @else
                                            <button class="btn btn-sm btn-light border rounded-circle text-muted" disabled title="No puedes desactivarte a ti mismo">
                                                <i class="bi bi-power"></i>
                                            </button>
                                        @endif
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" class="text-center py-5 text-muted">
                                    <i class="bi bi-people fs-1 d-block mb-3 text-light"></i>
                                    No se encontraron usuarios que coincidan con los filtros.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            @if($usuarios->hasPages())
                <div class="p-4 border-top">
                    {{ $usuarios->links('pagination::bootstrap-5') }}
                </div>
            @endif
        </div>
    </div>

    <!-- Modal para Crear Nuevo Usuario -->
    <div class="modal fade" id="createUserModal" tabindex="-1" aria-labelledby="createUserModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content border-0 shadow-lg rounded-4">
                <div class="modal-header bg-light border-bottom-0 pb-0 rounded-top-4 pt-4 px-4">
                    <h5 class="modal-title fw-bold" id="createUserModalLabel"><i class="bi bi-person-plus-fill text-primary me-2"></i> Registrar Nuevo Usuario</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <form method="POST" action="{{ route('admin.usuarios.store') }}" id="createUserForm">
                        @csrf

                        <div class="row g-4">
                            <!-- Nombre -->
                            <div class="col-md-6">
                                <label for="name_modal" class="form-label fw-bold small text-muted">Nombre Completo <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="name_modal" name="name" required autofocus>
                            </div>

                            <!-- Email -->
                            <div class="col-md-6">
                                <label for="email_modal" class="form-label fw-bold small text-muted">Correo Electrónico <span class="text-danger">*</span></label>
                                <input type="email" class="form-control" id="email_modal" name="email" required>
                                <span class="text-danger small" id="email_error" style="display:none;">Este correo ya está registrado.</span>
                            </div>

                            <!-- DNI -->
                            <div class="col-md-6">
                                <label for="dni_modal" class="form-label fw-bold small text-muted">DNI (Opcional)</label>
                                <input type="text" class="form-control" id="dni_modal" name="dni" maxlength="8" pattern="\d{8}">
                            </div>

                            <!-- Teléfono -->
                            <div class="col-md-6">
                                <label for="telefono_modal" class="form-label fw-bold small text-muted">Teléfono (Opcional)</label>
                                <input type="text" class="form-control" id="telefono_modal" name="telefono">
                            </div>

                            <!-- Password -->
                            <div class="col-md-6">
                                <label for="password_modal" class="form-label fw-bold small text-muted">Contraseña <span class="text-danger">*</span></label>
                                <input type="password" class="form-control" id="password_modal" name="password" required minlength="8">
                            </div>

                            <!-- Rol -->
                            <div class="col-md-6">
                                <label for="role_modal" class="form-label fw-bold small text-muted">Rol en el Sistema <span class="text-danger">*</span></label>
                                <select name="role" id="role_modal" class="form-select tom-select" required>
                                    <option value="">Seleccione un Rol</option>
                                    @foreach($roles as $r)
                                        <option value="{{ $r }}">{{ ucfirst($r) }}</option>
                                    @endforeach
                                </select>
                            </div>

                            <!-- Sucursales -->
                            <div class="col-md-12">
                                <label class="form-label fw-bold small text-muted">Sucursales Asignadas <span class="text-danger">*</span></label>
                                <div class="bg-light p-3 rounded-3 border">
                                    <div class="row g-2">
                                        @foreach($sucursales as $sucursal)
                                            <div class="col-md-4">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="sucursales[]" value="{{ $sucursal->id }}" id="sucursal_{{ $sucursal->id }}">
                                                    <label class="form-check-label small" for="sucursal_{{ $sucursal->id }}">
                                                        {{ $sucursal->nombre }}
                                                    </label>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Activo -->
                            <div class="col-md-6 d-flex align-items-center">
                                <div class="form-check form-switch mt-3 custom-switch fs-5">
                                    <input class="form-check-input" type="checkbox" role="switch" id="activo_modal" name="activo" value="1" checked>
                                    <label class="form-check-label fw-bold small ms-2 text-muted" for="activo_modal">Usuario Activo</label>
                                </div>
                            </div>
                        </div>

                        <div class="mt-4 pt-3 border-top text-end">
                            <button type="button" class="btn btn-light rounded-pill border fw-bold px-4 me-2 shadow-sm" data-bs-dismiss="modal">Cancelar</button>
                            <button type="submit" class="btn btn-primary rounded-pill fw-bold shadow-sm px-4" id="btn_submit_modal">
                                <i class="bi bi-check-lg me-1"></i> Guardar Usuario
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const emailInput = document.getElementById('email_modal');
            const emailError = document.getElementById('email_error');
            const btnSubmit = document.getElementById('btn_submit_modal');

            emailInput.addEventListener('blur', function () {
                const email = emailInput.value;
                if (!email) return;

                fetch(`/admin/usuarioS/verificar-email?email=${encodeURIComponent(email)}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.existe) {
                            emailInput.classList.add('is-invalid');
                            emailError.style.display = 'block';
                            btnSubmit.disabled = true;
                        } else {
                            emailInput.classList.remove('is-invalid');
                            emailError.style.display = 'none';
                            btnSubmit.disabled = false;
                        }
                    })
                    .catch(err => console.error(err));
            });
        });
    </script>
    @endpush

    @push('styles')
    <style>
        .disabled-hover:hover i { opacity: 0.7; }
    </style>
    @endpush
</x-app-layout>
