@extends('layouts.app')

@section('title', 'Usuarios')
@section('page-title', 'Gestión de Usuarios')

@section('content')
<div class="row mb-4">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center">
            <h2>Usuarios del Sistema</h2>
            <a href="{{ route('users.create') }}" class="btn btn-primary">
                <i class="bi bi-plus-circle me-2"></i>Nuevo Usuario
            </a>
        </div>
    </div>
</div>

@if(session('success'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
    <i class="bi bi-check-circle me-2"></i>
    <div>{{ session('success') }}</div>
    @if(session('success') && strpos(session('success'), 'Link de activación') !== false)
        <div class="mt-2">
            <button class="btn btn-sm btn-success" onclick="copyActivationLink()">
                <i class="bi bi-clipboard me-1"></i>Copiar enlace
            </button>
        </div>
        <script>
            // Extraer el link del mensaje
            const successMessage = '{{ session('success') }}';
            const linkMatch = successMessage.match(/http[s]?:\/\/[^\s]+/);
            const activationLink = linkMatch ? linkMatch[0] : '';
            
            function copyActivationLink() {
                if (activationLink) {
                    navigator.clipboard.writeText(activationLink).then(function() {
                        alert('Enlace de activación copiado al portapapeles');
                    }, function() {
                        alert('No se pudo copiar el enlace');
                    });
                }
            }
        </script>
    @endif
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
@endif

@if(session('error'))
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <i class="bi bi-exclamation-triangle me-2"></i>{{ session('error') }}
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
@endif

<!-- Filtros por rol -->
<div class="card mb-4">
    <div class="card-body">
        <div class="btn-group" role="group">
            <button type="button" class="btn btn-outline-primary active" onclick="filterByRole('all')">
                Todos ({{ $users->count() }})
            </button>
            <button type="button" class="btn btn-outline-primary" onclick="filterByRole('administrador')">
                Administradores ({{ $users->where('role', 'administrador')->count() }})
            </button>
            <button type="button" class="btn btn-outline-primary" onclick="filterByRole('supervisor')">
                Supervisores N3 ({{ $users->where('role', 'supervisor')->count() }})
            </button>
            <button type="button" class="btn btn-outline-primary" onclick="filterByRole('ingeniero')">
                Ingenieros N2 ({{ $users->where('role', 'ingeniero')->count() }})
            </button>
            <button type="button" class="btn btn-outline-primary" onclick="filterByRole('responsable')">
                Técnicos N1 ({{ $users->where('role', 'responsable')->count() }})
            </button>
            <button type="button" class="btn btn-outline-primary" onclick="filterByRole('solicitante')">
                Clientes ({{ $users->where('role', 'solicitante')->count() }})
            </button>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Usuario</th>
                        <th>Rol</th>
                        <th>Empresa</th>
                        <th>Estado</th>
                        <th>Tickets</th>
                        <th>Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($users as $user)
                    <tr class="user-row" data-role="{{ $user->role }}">
                        <td>
                            <div class="d-flex align-items-center">
                                <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-3" 
                                     style="width: 40px; height: 40px; font-size: 18px;">
                                    {{ substr($user->name, 0, 1) }}
                                </div>
                                <div>
                                    <div class="fw-bold">{{ $user->name }}</div>
                                    <small class="text-muted">{{ $user->email }}</small>
                                    @if($user->position)
                                    <br><small class="text-muted"><i class="bi bi-briefcase"></i> {{ $user->position }}</small>
                                    @endif
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="badge {{ role_badge_class($user->role) }}">
                                {{ role_name($user->role) }}
                            </span>
                        </td>
                        <td>
                            @if($user->company)
                                <small>{{ $user->company->name }}</small>
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>
                            @if($user->is_active)
                            <span class="badge bg-success">Activo</span>
                            @else
                            <span class="badge bg-secondary">Inactivo</span>
                            @endif
                        </td>
                        <td>
                            <small class="text-muted">
                                Creados: {{ $user->createdTickets()->count() }}<br>
                                Asignados: {{ $user->assignedTickets()->count() }}
                            </small>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                @if(in_array($user->role, ['responsable', 'ingeniero', 'supervisor']))
                                <a href="{{ route('users.assign-projects', $user) }}" class="btn btn-outline-success" title="Asignar Proyectos">
                                    <i class="bi bi-building-gear"></i>
                                </a>
                                @endif
                                <a href="{{ route('users.show', $user) }}" class="btn btn-outline-primary" title="Ver">
                                    <i class="bi bi-eye"></i>
                                </a>
                                <a href="{{ route('users.edit', $user) }}" class="btn btn-outline-secondary" title="Editar">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                @if($user->id !== auth()->id())
                                <form action="{{ route('users.destroy', $user) }}" method="POST" class="d-inline"
                                      onsubmit="return confirm('¿Estás seguro de eliminar este usuario?')">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn btn-outline-danger" title="Eliminar">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                                @endif
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" class="text-center py-5">
                            <i class="bi bi-people display-1 text-muted mb-3 d-block"></i>
                            <p class="text-muted">No hay usuarios registrados</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>

@push('scripts')
<script>
function filterByRole(role) {
    const rows = document.querySelectorAll('.user-row');
    const buttons = document.querySelectorAll('.btn-group button');
    
    // Actualizar botones activos
    buttons.forEach(btn => btn.classList.remove('active'));
    event.target.classList.add('active');
    
    // Filtrar filas
    rows.forEach(row => {
        if (role === 'all' || row.dataset.role === role) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}
</script>
@endpush
@endsection
