@extends('layouts.ownerLayout')

@section('title', 'Equipo')

@section('vendor-style')
@vite([
  'resources/assets/vendor/libs/datatables-bs5/datatables.bootstrap5.scss',
  'resources/assets/vendor/libs/datatables-responsive-bs5/responsive.bootstrap5.scss',
  'resources/assets/vendor/libs/datatables-buttons-bs5/buttons.bootstrap5.scss',
  'resources/assets/vendor/libs/@form-validation/form-validation.scss',
  'resources/assets/vendor/libs/animate-css/animate.scss',
  'resources/assets/vendor/libs/sweetalert2/sweetalert2.scss',
  'resources/assets/vendor/libs/notyf/notyf.scss'
])
@endsection

@section('vendor-script')
@vite([
  'resources/assets/vendor/libs/datatables-bs5/datatables-bootstrap5.js',
  'resources/assets/vendor/libs/sweetalert2/sweetalert2.js',
  'resources/assets/vendor/libs/notyf/notyf.js',
  'resources/assets/vendor/libs/@form-validation/popular.js',
  'resources/assets/vendor/libs/@form-validation/bootstrap5.js',
  'resources/assets/vendor/libs/@form-validation/auto-focus.js'
])
@endsection

@section('page-script')
  @vite('resources/assets/js/owner-team.js')
  <script>
    window.__openAddTeamUser = @json($errors->any());
    window.__toastData = {
      success: @json(session('status')),
      errors: @json($errors->all())
    };
    window.__swalData = {
      success: @json(session('swal_success'))
    };
    window.__canManageTeam = @json($canManageTeam);
  </script>
@endsection

@section('content')
<div class="row g-6 mb-6">
  <div class="col-sm-6 col-xl-4">
    <div class="card">
      <div class="card-body">
        <span class="text-heading">Total equipo</span>
        <h4 class="mb-0 mt-1">{{ number_format($stats['total']) }}</h4>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-xl-4">
    <div class="card">
      <div class="card-body">
        <span class="text-heading">Activos</span>
        <h4 class="mb-0 mt-1">{{ number_format($stats['active']) }}</h4>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-xl-4">
    <div class="card">
      <div class="card-body">
        <span class="text-heading">Inactivos</span>
        <h4 class="mb-0 mt-1">{{ number_format($stats['inactive']) }}</h4>
      </div>
    </div>
  </div>
</div>

@if (!$canManageTeam)
  <div class="alert alert-warning">
    Tu usuario no tiene organización asignada. Solicita al administrador asociarte a una organización para gestionar equipo.
  </div>
@endif

<div class="card">
  <div class="card-header border-bottom">
    <h5 class="card-title mb-0">Equipo</h5>
    <div class="d-flex justify-content-between align-items-center row pt-4 gap-4 gap-md-0">
      <div class="col-md-6 owner_team_role"></div>
      <div class="col-md-6 owner_team_status"></div>
    </div>
  </div>

  <div class="card-datatable">
    <table class="datatables-owner-team table border-top">
      <thead>
        <tr>
          <th>ID</th>
          <th>Usuario</th>
          <th>Rol</th>
          <th>Equipos</th>
          <th>Estado</th>
          <th>Acciones</th>
        </tr>
      </thead>
      <tbody>
        @foreach ($users as $user)
          <tr>
            <td>{{ $user->id }}</td>
            <td>
              <div class="d-flex flex-column">
                <span class="fw-medium text-heading">{{ $user->name }}</span>
                <small>{{ $user->email }}</small>
              </div>
            </td>
            <td>
              <span class="badge bg-label-info">{{ $user->current_role_name ?: 'Sin rol' }}</span>
            </td>
            <td>
              @if ($user->has_all_mariachi_groups)
                <span class="badge bg-label-primary">Todos los equipos</span>
              @elseif ($user->assignedMariachiGroups->isNotEmpty())
                <div class="d-flex flex-wrap gap-1">
                  @foreach ($user->assignedMariachiGroups as $group)
                    <span class="badge bg-label-warning">{{ $group->name }}</span>
                  @endforeach
                </div>
              @else
                <span class="text-body-secondary">Sin equipos</span>
              @endif
            </td>
            <td>
              <span class="badge {{ $user->is_active ? 'bg-label-success' : 'bg-label-secondary' }}">
                {{ $user->is_active ? 'Activo' : 'Inactivo' }}
              </span>
            </td>
            <td>
              @if ($user->is_active)
                <form action="{{ route('owner.settings.team.deactivate', $user) }}" method="POST">
                  @csrf
                  @method('PATCH')
                  <button type="submit" class="btn btn-text-secondary rounded-pill waves-effect btn-icon btn-deactivate-owner-team-user" title="Desactivar">
                    <i class="icon-base ti tabler-user-x icon-22px"></i>
                  </button>
                </form>
              @endif
            </td>
          </tr>
        @endforeach
      </tbody>
    </table>
  </div>

  <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasAddOwnerTeamUser" aria-labelledby="offcanvasAddOwnerTeamUserLabel">
    <div class="offcanvas-header border-bottom">
      <h5 id="offcanvasAddOwnerTeamUserLabel" class="offcanvas-title">Agregar miembro</h5>
      <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body mx-0 flex-grow-0 p-6 h-100">
      <form class="add-new-user pt-0" id="addNewOwnerTeamUserForm" method="POST" action="{{ route('owner.settings.team.store') }}">
        @csrf

        <div class="mb-6 form-control-validation">
          <label class="form-label" for="owner_team_name">Nombre</label>
          <input type="text" class="form-control" id="owner_team_name" name="name" placeholder="Nombre completo" value="{{ old('name') }}" required>
        </div>

        <div class="mb-6 form-control-validation">
          <label class="form-label" for="owner_team_email">Correo</label>
          <input type="email" id="owner_team_email" class="form-control" placeholder="correo@empresa.com" name="email" value="{{ old('email') }}" required>
        </div>

        <div class="mb-6 form-control-validation">
          <label class="form-label" for="owner_team_password">Contraseña</label>
          <input type="password" id="owner_team_password" class="form-control" name="password" placeholder="Mínimo 8 caracteres" required>
        </div>

        <div class="mb-6 form-control-validation">
          <label class="form-label" for="owner_team_staff_role">Rol</label>
          <select id="owner_team_staff_role" class="form-select" name="staff_role">
            @forelse ($staffRoles as $staffRole)
              <option value="{{ $staffRole->code }}" @selected(old('staff_role') === $staffRole->code)>{{ $staffRole->name }} ({{ $staffRole->code }})</option>
            @empty
              <option value="">No hay roles disponibles</option>
            @endforelse
          </select>
        </div>

        <div class="mb-6 form-control-validation">
          <input type="hidden" name="has_all_mariachi_groups" value="0">
          <div class="form-check">
            <input
              type="checkbox"
              class="form-check-input"
              id="owner_team_has_all_mariachi_groups"
              name="has_all_mariachi_groups"
              value="1"
              @checked((string) old('has_all_mariachi_groups', '1') === '1')>
            <label class="form-check-label" for="owner_team_has_all_mariachi_groups">
              Acceso a todos los equipos de la organización
            </label>
          </div>
        </div>

        <div class="mb-6 form-control-validation">
          <label class="form-label" for="owner_team_mariachi_group_ids">Equipos asignados</label>
          <select id="owner_team_mariachi_group_ids" class="form-select" name="mariachi_group_ids[]" multiple size="5">
            @foreach ($mariachiGroups as $group)
              <option value="{{ $group->id }}" @selected(collect(old('mariachi_group_ids', []))->contains((string) $group->id) || collect(old('mariachi_group_ids', []))->contains($group->id))>
                {{ $group->name }}
              </option>
            @endforeach
          </select>
          <small class="text-body-secondary">Si desactivas “todos los equipos”, este usuario solo podrá operar los grupos seleccionados y la vista “Todos” será la suma de esos grupos.</small>
          @error('mariachi_group_ids')
            <div class="invalid-feedback d-block">{{ $message }}</div>
          @enderror
        </div>

        <div class="mb-6 form-control-validation">
          <label class="form-label" for="owner_team_is_active">Estado</label>
          <select id="owner_team_is_active" class="form-select" name="is_active" required>
            <option value="1" @selected((string) old('is_active', '1') === '1')>Activo</option>
            <option value="0" @selected((string) old('is_active', '1') === '0')>Inactivo</option>
          </select>
        </div>

        <button type="submit" class="btn btn-primary me-3" @disabled(!$canManageTeam || $staffRoles->isEmpty())>Guardar</button>
        <button type="reset" class="btn btn-label-danger" data-bs-dismiss="offcanvas">Cancelar</button>
      </form>
    </div>
  </div>
</div>
@endsection
