@extends('layouts.admin.theme')
@section("title", env("APP_NAME") . " :: " . __("Lista de Usuário"))
@section('content')

    <div class="card shadow-sm">

        @php $headLine = "<i class='fa-solid fa-user-gear'></i> Lista de Usuário"; @endphp

        @include('components.buttons._headLineButtonsBackAdd', [
            'headLine' => __($headLine),
//            'routeBack' => 'admin.turismoNautico.index',
//            'routeBackParams' => [],
//            'nameBack' => __("Voltar"),
            'routeAdd' => 'admin.contas.create',
            'routeAddParams' => [],
            'nameAdd' => __('Novo usuário'),
            "permission" => "SYSADMIN",
        ])

        <div class="card-body">
            <div class="mb-3">
                <span class="badge bg-primary fs-6">
                    <i class="fa-solid fa-users me-1"></i>
                    {{ __('Total de usuários') }}: <strong>{{ number_format($totalUsuarios, 0, ',', '.') }}</strong>
                </span>
            </div>

            @include("errors.messageFlash")

            @php
                use App\Http\Resources\Accounts\AccountResource;
                $hasActiveFilters = request()->filled('q')
                    || request()->filled('structure_id')
                    || request()->filled('status')
                    || AccountResource::hasActivePermissionFilter(request());
            @endphp

            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-light border-bottom">
                    <h5 class="mb-0">
                        <i class="fa-solid fa-filter me-2 text-primary"></i>
                        {{ __('Filtros de Busca') }}
                    </h5>
                </div>
                <div class="card-body">
                    <form id="cadastroDeUsuario" method="get">
                        <input type="hidden" name="page" value="1">
                        <input type="hidden" name="sort_by" value="{{ request()->input('sort_by', 'created_at') }}">
                        <input type="hidden" name="sort_dir" value="{{ request()->input('sort_dir', 'desc') }}">

                        <div class="row g-2 align-items-end">
                            <div class="col-12 col-lg-4">
                                <label for="filtro_q" class="form-label fw-semibold">
                                    <i class="fa-solid fa-magnifying-glass me-1 text-muted"></i>
                                    {{ __('Pesquisar') }}
                                </label>
                                <div class="input-group">
                                    <span class="input-group-text bg-light">
                                        <i class="fa-solid fa-user text-muted"></i>
                                    </span>
                                    <input
                                        type="text"
                                        id="filtro_q"
                                        class="form-control"
                                        name="q"
                                        placeholder="{{ __('Nome, matrícula, e-mail ou CPF...') }}"
                                        value="{{ request()->input('q') }}"
                                    >
                                </div>
                            </div>

                            <div class="col-12 col-lg-3">
                                <label for="filtro_structure_id" class="form-label fw-semibold">
                                    <i class="fa-solid fa-building me-1 text-muted"></i>
                                    {{ __('Pertence a') }}
                                </label>
                                <div class="input-group">
                                    <span class="input-group-text bg-light">
                                        <i class="fa-solid fa-sitemap text-muted"></i>
                                    </span>
                                    <select
                                        id="filtro_structure_id"
                                        name="structure_id"
                                        class="form-select"
                                    >
                                        <option value="">{{ __('Todas as secretarias') }}</option>
                                        @foreach($secretarias as $secretaria)
                                            <option value="{{ $secretaria->id }}"
                                                @selected(request()->input('structure_id') === $secretaria->id)>
                                                {{ $secretaria->name }} ({{ $secretaria->abbreviation }})
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                            <div class="col-12 col-lg-2">
                                <label for="filtro_status" class="form-label fw-semibold">
                                    <i class="fa-solid fa-toggle-on me-1 text-muted"></i>
                                    {{ __('Status') }}
                                </label>
                                <div class="input-group">
                                    <span class="input-group-text bg-light">
                                        <i class="fa-solid fa-circle-check text-muted"></i>
                                    </span>
                                    <select
                                        id="filtro_status"
                                        name="status"
                                        class="form-select"
                                    >
                                        <option value="">{{ __('Todos') }}</option>
                                        <option value="ATIVADO" @selected(request()->input('status') === 'ATIVADO')>{{ __('Ativos') }}</option>
                                        <option value="DESATIVADO" @selected(request()->input('status') === 'DESATIVADO')>{{ __('Inativos') }}</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-12 col-lg-3">
                                <div class="d-flex flex-wrap gap-2">
                                    <button class="btn btn-primary flex-fill" type="submit">
                                        <i class="fa-solid fa-magnifying-glass me-1"></i>
                                        {{ __('Filtrar') }}
                                    </button>
                                    @include('components.contas._permissionsFilterModal', [
                                        'permissoesDisponiveis' => $permissoesDisponiveis,
                                        'permissionFilterState' => $permissionFilterState,
                                    ])
                                    <a href="{{ route('admin.contas.index') }}" class="btn btn-outline-secondary">
                                        <i class="fa-solid fa-rotate-left me-1"></i>
                                        {{ __('Limpar') }}
                                    </a>
                                </div>
                            </div>
                        </div>

                        @if($hasActiveFilters)
                            <div class="row mt-3">
                                <div class="col-12">
                                    <div class="d-flex flex-wrap gap-2 align-items-center">
                                        <small class="text-muted fw-semibold me-2">
                                            <i class="fa-solid fa-info-circle me-1"></i>
                                            {{ __('Filtros ativos:') }}
                                        </small>
                                        @if(request()->filled('q'))
                                            <span class="badge bg-secondary">
                                                <i class="fa-solid fa-magnifying-glass me-1"></i>
                                                {{ __('Busca') }}: "{{ request()->input('q') }}"
                                                <button type="button" class="btn-close btn-close-white ms-2" style="font-size: 0.7em;" onclick="document.getElementById('filtro_q').value=''; this.closest('form').submit();"></button>
                                            </span>
                                        @endif
                                        @if(request()->filled('structure_id'))
                                            @php
                                                $selectedSecretaria = $secretarias->firstWhere('id', request()->input('structure_id'));
                                            @endphp
                                            @if($selectedSecretaria)
                                                <span class="badge bg-primary">
                                                    <i class="fa-solid fa-building me-1"></i>
                                                    {{ $selectedSecretaria->name }}
                                                    <button type="button" class="btn-close btn-close-white ms-2" style="font-size: 0.7em;" onclick="document.getElementById('filtro_structure_id').value=''; this.closest('form').submit();"></button>
                                                </span>
                                            @endif
                                        @endif
                                        @if(request()->filled('status'))
                                            <span class="badge bg-{{ request()->input('status') === 'ATIVADO' ? 'success' : 'secondary' }}">
                                                <i class="fa-solid fa-toggle-{{ request()->input('status') === 'ATIVADO' ? 'on' : 'off' }} me-1"></i>
                                                {{ request()->input('status') === 'ATIVADO' ? __('Ativos') : __('Inativos') }}
                                                <button type="button" class="btn-close btn-close-white ms-2" style="font-size: 0.7em;" onclick="document.getElementById('filtro_status').value=''; this.closest('form').submit();"></button>
                                            </span>
                                        @endif
                                        @if(count($permissionFilterState) > 0)
                                            <span class="badge bg-info">
                                                <i class="fa-solid fa-shield-halved me-1"></i>
                                                {{ count($permissionFilterState) }} {{ __('permissões') }}
                                                · {{ AccountResource::filterModeLabel(request()->input('permissao_modo', 'any')) }}
                                            </span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        @endif
                    </form>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover table-striped align-middle text-center">
                            <thead class="table-light">
                                <tr>
                                    <th style="width:150px">#</th>
                                    <th class="text-center">
                                        @php
                                            $sortParams = AccountResource::listFilterQueryParams(request());
                                            unset($sortParams['page'], $sortParams['sort_by'], $sortParams['sort_dir']);
                                            $sortParams['sort_by'] = 'created_at';
                                            $sortParams['sort_dir'] = request('sort_by') == 'created_at' && request('sort_dir') == 'asc' ? 'desc' : 'asc';
                                        @endphp
                                        <a href="?{{ http_build_query($sortParams) }}"
                                            class="text-decoration-none text-dark">
                                            {{ __('Criado em') }}
                                            @if(request('sort_by') == 'created_at' || (!request()->has('sort_by') && !request()->has('sort_dir')))
                                                <i class="fa fa-sort-{{ (request('sort_dir', 'desc') == 'asc') ? 'up' : 'down' }}"></i>
                                            @else
                                                <i class="fa fa-sort text-muted"></i>
                                            @endif
                                        </a>
                                    </th>
                                    <th>{{ __('Usuário') }}</th>
                                    <th>{{ __('CPF') }}</th>
                                    <th>{{ __('E-mail') }}</th>
                                    <th>{{ __('Status') }}</th>
                                    <th>{{ __('Ações') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php $index = 0; @endphp
                                @forelse($users as $user)
                                    <tr>
                                        <td style="width:150px">
                                            @include('components.tables._openPhoto', [
                                                'asset' => $user->photo,
                                                'alt' => $user->name,
                                                'title' => $user->name,
                                                'text' => 'Visualizar foto',
                                            ])
                                        </td>
                                        <td>{{ date("d/m/Y H:i", strtotime($user->created_at)) }}</td>
                                        <td>
                                            <strong>Nome: </strong>{{ $user->name }}<br>
                                            @if($user->matriculation)
                                                <strong>Matrícula: </strong>{{ $user->matriculation }}<br>
                                            @endif
                                            <strong>Pertence a: </strong>{{ $user->pertence->name ?? '-' }}<br>
                                        </td>
                                        <td>{{ $user->cpf }}</td>
                                        <td>{{ $user->email }}</td>
                                        <td class="text-center align-middle">
                                            @if (auth()->user()->getPermissaoDetalhes("SYSADMIN")['editar'])
                                                <form id="{{ "checkStatus_" . $index }}" class="fix" action="{{ route("admin.contas.status", $user->id)}}" method="post">
                                                    @csrf
                                                    @include('components.contas._accountListFilterHiddenFields')
                                                    @if($user->status == "ATIVADO" || $user->status == 1 )
                                                        <div class="form-check form-switch d-flex justify-content-center">
                                                            <input type="hidden" name="checkStatus" value="DESATIVADO">
                                                            <input class="form-check-input" type="checkbox" checked
                                                               onclick="javascript:document.getElementById('checkStatus_{{ $index }}').submit()">
                                                        </div>
                                                    @else
                                                        <div class="form-check form-switch d-flex justify-content-center">
                                                            <input type="hidden" name="checkStatus" value="ATIVADO">
                                                            <input class="form-check-input" type="checkbox"
                                                               onclick="javascript:document.getElementById('checkStatus_{{ $index }}').submit()">
                                                        </div>
                                                    @endif
                                                </form>
                                            @endif
                                        </td>
                                        <td>
                                            <div class="d-flex gap-2 justify-content-center">
                                                @php
                                                    $filterQueryString = http_build_query(array_filter(
                                                        \App\Http\Resources\Accounts\AccountResource::listFilterQueryParams(request())
                                                    ));
                                                    $editUrl = route("admin.contas.edit", $user->id) . ($filterQueryString ? '?' . $filterQueryString : '');
                                                @endphp
                                                @include('components.buttons._navButton', [
                                                    "route" => "admin.contas.enderecos.index",
                                                    "id" => $user->id,
                                                    "fontawesome" => '<i class="fa-solid fa-location-dot" data-bs-toggle="tooltip" title="Gerenciar Endereços"></i>',
                                                    "title" => "Endereços",
                                                ])

                                                @if (auth()->user()->getPermissaoDetalhes("SYSADMIN")['editar'])
                                                    <a href="{{ $editUrl }}" class="btn btn-sm btn-warning" title="{{ __('Editar') }}">
                                                        <i class="fa-solid fa-pen-to-square"></i>
                                                    </a>
                                                @endif

                                                @if (auth()->user()->getPermissaoDetalhes("SYSADMIN")['excluir'])
                                                    <form class="d-inline" action="{{ route("admin.contas.destroy", $user->id) }}" method="post" onsubmit="return confirmDelete(this)">
                                                        @csrf
                                                        @method('delete')
                                                        @include('components.contas._accountListFilterHiddenFields')
                                                        <input type="hidden" name="confirm" value="{{ __('* Este usuário será excluído e esta ação não poderá ser desfeita, deseja continuar?') }}">
                                                        <button type="submit" class="btn btn-sm btn-danger" title="{{ __('Excluir') }}">
                                                            <i class="fa-solid fa-trash"></i>
                                                        </button>
                                                    </form>
                                                @endif
                                            </div>
                                        </td>
                                    </tr>
                                    @php $index++; @endphp
                                @empty
                                    <tr>
                                        <td colspan="7">{{ __('* Nenhum registro encontrado') }}</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>

                @if($users->hasPages())
                    <div class="col-12 my-3">
                        <div class="d-flex justify-content-center">
                            {{ $users->links() }}
                        </div>
                    </div>
                @endif
            </div>

        </div>
    </div>

    <style>
        /* Melhorias visuais para os filtros */
        .card-header.bg-light {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%) !important;
        }

        .input-group-text {
            border-right: none;
            transition: all 0.3s ease;
        }

        .form-control:focus,
        .form-select:focus {
            border-left: none;
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.15);
        }

        .input-group:focus-within .input-group-text {
            background-color: #e7f1ff;
            border-color: #86b7fe;
        }

        .badge {
            font-size: 0.85rem;
            padding: 0.5rem 0.75rem;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }

        .badge .btn-close {
            opacity: 0.8;
            transition: opacity 0.2s ease;
        }

        .badge .btn-close:hover {
            opacity: 1;
        }

        .btn-primary {
            box-shadow: 0 2px 4px rgba(13, 110, 253, 0.2);
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(13, 110, 253, 0.3);
        }

        .btn-outline-secondary {
            transition: all 0.3s ease;
            min-width: 100px;
        }

        .btn-outline-secondary:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(108, 117, 125, 0.2);
        }

        .d-flex.gap-2 {
            align-items: stretch;
        }

        @media (max-width: 991px) {
            .d-flex.gap-2 {
                flex-direction: column;
            }

            .d-flex.gap-2 .btn {
                width: 100%;
            }
        }

        .form-label {
            font-size: 0.875rem;
            margin-bottom: 0.5rem;
        }

        @media (max-width: 768px) {
            .card-header .d-flex {
                flex-direction: column;
                gap: 0.5rem;
                align-items: flex-start !important;
            }

            .badge {
                font-size: 0.75rem;
                padding: 0.4rem 0.6rem;
            }
        }

        /* Animação suave para os badges de filtros ativos */
        .badge {
            animation: fadeIn 0.3s ease-in;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-5px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
@endsection
