<!-- [DEF:AdminUsersPage:Component] -->
<!--
@SEMANTICS: admin, user-management, rbac
@PURPOSE:   UI for managing system users and their roles.
@LAYER:     Feature
@RELATION:  DEPENDS_ON -> frontend.src.services.adminService
@RELATION:  DEPENDS_ON -> frontend.src.components.auth.ProtectedRoute

@INVARIANT: Only accessible by users with "admin:users" permission.
-->

<script lang="ts">
  // [SECTION: IMPORTS]
  import { onMount } from 'svelte';
  import { t } from '$lib/i18n';
  import ProtectedRoute from '../../../components/auth/ProtectedRoute.svelte';
  import { adminService } from '../../../services/adminService';
  // [/SECTION: IMPORTS]

  let users = [];
  let roles = [];
  let loading = true;
  let error = null;
  let deletingUserId = null;

  let showModal = false;
  let isEditing = false;
  let currentUserId = null;
  let userForm = {
    username: '',
    email: '',
    password: '',
    roles: [],
    is_active: true
  };

  // [DEF:loadData:Function]
  /**
   * @purpose Fetches users and roles from the backend.
   * @pre     Component mounted.
   * @post    users and roles arrays populated.
   */
  async function loadData() {
    console.log('[AdminUsersPage][loadData][Entry]');
    loading = true;
    try {
      [users, roles] = await Promise.all([
        adminService.getUsers(),
        adminService.getRoles()
      ]);
      console.log('[AdminUsersPage][loadData][Coherence:OK]');
    } catch (e) {
      error = $t.admin?.users?.load_failed ;
      console.error('[AdminUsersPage][loadData][Coherence:Failed]', e);
    } finally {
      loading = false;
    }
  }
  // [/DEF:loadData:Function]

  // [DEF:openCreateModal:Function]
  /**
   * @purpose Prepares the form for creating a new user.
   * @post    showModal is true, isEditing is false, userForm is reset.
   */
  function openCreateModal() {
    isEditing = false;
    currentUserId = null;
    userForm = { username: '', email: '', password: '', roles: [], is_active: true };
    showModal = true;
  }
  // [/DEF:openCreateModal:Function]

  // [DEF:openEditModal:Function]
  /**
   * @purpose Prepares the form for editing an existing user.
   * @pre     user object must be valid.
   * @post    showModal is true, isEditing is true, userForm populated with user data.
   * @param   {Object} user - The user object to edit.
   */
  function openEditModal(user) {
    isEditing = true;
    currentUserId = user.id;
    userForm = {
      username: user.username,
      email: user.email,
      password: '',
      roles: user.roles.map(r => r.name),
      is_active: user.is_active
    };
    showModal = true;
  }
  // [/DEF:openEditModal:Function]

  // [DEF:handleSaveUser:Function]
  /**
   * @purpose Submits user data to the backend (create or update).
   * @pre     userForm must be valid.
   * @post    User created or updated, modal closed, data reloaded.
   * @side_effect Triggers API call to adminService.
   * @relation CALLS -> adminService.createUser
   * @relation CALLS -> adminService.updateUser
   */
  async function handleSaveUser() {
    console.log('[AdminUsersPage][handleSaveUser][Entry]');
    try {
      if (isEditing) {
        const updateData = { ...userForm };
        if (!updateData.password) delete updateData.password;
        await adminService.updateUser(currentUserId, updateData);
      } else {
        await adminService.createUser(userForm);
      }
      showModal = false;
      await loadData();
      console.log('[AdminUsersPage][handleSaveUser][Coherence:OK]');
    } catch (e) {
      alert(($t.admin?.users?.save_failed ).replace('{error}', e.message));
      console.error('[AdminUsersPage][handleSaveUser][Coherence:Failed]', e);
    }
  }
  // [/DEF:handleSaveUser:Function]

  // [DEF:handleDeleteUser:Function]
  /**
   * @purpose Deletes a user after confirmation.
   * @pre     user object must be valid.
   * @post    User deleted if confirmed, data reloaded.
   * @side_effect Triggers API call to adminService.
   * @relation CALLS -> adminService.deleteUser
   * @param   {Object} user - The user to delete.
   */
  async function handleDeleteUser(user) {
    if (deletingUserId) return;
    if (!confirm($t.admin.users.confirm_delete.replace('{username}', user.username))) return;
    
    console.log('[AdminUsersPage][handleDeleteUser][Entry]');
    deletingUserId = user.id;
    try {
      await adminService.deleteUser(user.id);
      await loadData();
      console.log('[AdminUsersPage][handleDeleteUser][Coherence:OK]');
    } catch (e) {
      alert(($t.admin?.users?.delete_failed ).replace('{error}', e.message));
      console.error('[AdminUsersPage][handleDeleteUser][Coherence:Failed]', e);
    } finally {
      deletingUserId = null;
    }
  }
  // [/DEF:handleDeleteUser:Function]

  onMount(loadData);
</script>

<ProtectedRoute requiredPermission="admin:users">
  <!-- [SECTION: TEMPLATE] -->
  <div class="container mx-auto p-4">
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold">{$t.admin.users.title}</h1>
      <button
        class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition-colors"
        onclick={openCreateModal}
      >
        {$t.admin.users.create}
      </button>
    </div>

    {#if loading}
      <div class="flex justify-center py-8">
        <p class="text-gray-500 animate-pulse">{$t.common.loading}</p>
      </div>
    {:else if error}
      <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded mb-4">
        <p class="font-bold">{$t.common.error}</p>
        <p>{error}</p>
      </div>
    {:else}
      <div class="bg-white shadow rounded-lg overflow-hidden border border-gray-200">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.admin.users.username}</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.admin.users.email}</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.admin.users.source}</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.admin.users.roles}</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.admin.users.status}</th>
              <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.common.actions}</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            {#each users as user}
              <tr class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap font-medium">{user.username}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{user.email || '-'}</td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span class="px-2 py-1 text-xs font-semibold rounded-full {user.auth_source === 'LOCAL' ? 'bg-blue-100 text-blue-800' : 'bg-green-100 text-green-800'}">
                    {user.auth_source}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="flex flex-wrap gap-1">
                    {#each user.roles as role}
                      <span class="px-2 py-0.5 bg-gray-100 text-gray-700 text-xs rounded border border-gray-200">{role.name}</span>
                    {/each}
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span class="flex items-center">
                    <span class="h-2 w-2 rounded-full mr-2 {user.is_active ? 'bg-green-500' : 'bg-red-500'}"></span>
                    <span class="text-sm {user.is_active ? 'text-green-700' : 'text-red-700'}">
                      {user.is_active ? $t.admin.users.active : $t.admin.users.inactive}
                    </span>
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <button onclick={() => openEditModal(user)} class="text-blue-600 hover:text-blue-900 mr-3" disabled={deletingUserId === user.id}>{$t.common.edit}</button>
                  <button
                    onclick={() => handleDeleteUser(user)}
                    class="text-red-600 hover:text-red-900 disabled:opacity-50"
                    disabled={deletingUserId === user.id}
                  >
                    {deletingUserId === user.id ? ($t.common.deleting ) : $t.common.delete}
                  </button>
                </td>
              </tr>
            {/each}
          </tbody>
        </table>
      </div>
    {/if}

    {#if showModal}
      <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-lg shadow-xl p-6 max-w-md w-full">
          <h2 class="text-xl font-bold mb-4 border-b pb-2">
            {isEditing ? $t.admin.users.modal_edit_title : $t.admin.users.modal_title}
          </h2>
          <form onsubmit={(event) => {
            event.preventDefault();
            handleSaveUser();
          }}>
            <div class="mb-4">
              <label for="admin-user-username" class="block text-sm font-medium text-gray-700 mb-1">{$t.admin.users.username}</label>
              <input id="admin-user-username" type="text" bind:value={userForm.username} class="w-full border border-gray-300 p-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-gray-50" required readonly={isEditing} />
            </div>
            <div class="mb-4">
              <label for="admin-user-email" class="block text-sm font-medium text-gray-700 mb-1">{$t.admin.users.email}</label>
              <input id="admin-user-email" type="email" bind:value={userForm.email} class="w-full border border-gray-300 p-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500" required />
            </div>
            <div class="mb-4">
              <label for="admin-user-password" class="block text-sm font-medium text-gray-700 mb-1">{$t.admin.users.password}</label>
              <input id="admin-user-password" type="password" bind:value={userForm.password} class="w-full border border-gray-300 p-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500" required={!isEditing} />
              {#if isEditing}
                <p class="text-xs text-gray-500 mt-1">{$t.admin.users.password_hint}</p>
              {/if}
            </div>
            <div class="mb-4">
              <label class="flex items-center space-x-2 cursor-pointer">
                <input type="checkbox" bind:checked={userForm.is_active} class="rounded text-blue-600 focus:ring-blue-500" />
                <span class="text-sm font-medium text-gray-700">{$t.admin.users.active}</span>
              </label>
            </div>
            <div class="mb-6">
              <label for="admin-user-roles" class="block text-sm font-medium text-gray-700 mb-1">{$t.admin.users.roles}</label>
              <select id="admin-user-roles" multiple bind:value={userForm.roles} class="w-full border border-gray-300 p-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500 h-32">
                {#each roles as role}
                  <option value={role.name}>{role.name}</option>
                {/each}
              </select>
              <p class="text-xs text-gray-500 mt-1">{$t.admin.users.roles_hint}</p>
            </div>
            <div class="flex justify-end gap-3 pt-4 border-t">
              <button type="button" class="px-4 py-2 text-gray-600 hover:text-gray-800 font-medium" onclick={() => showModal = false}>{$t.common.cancel}</button>
              <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded font-bold hover:bg-blue-700 shadow-md transition-colors">{$t.common.save}</button>
            </div>
          </form>
        </div>
      </div>
    {/if}
  </div>
  <!-- [/SECTION: TEMPLATE] -->
</ProtectedRoute>


<!-- [/DEF:AdminUsersPage:Component] -->
