<script lang="ts">
  import type { SubmitFunction } from "@sveltejs/kit";
  import EmailText from "../../../components/EmailText.svelte";
  import type { PermissionMap } from "$lib/permissions";
  import type { User } from "$lib/optima-api/modules/users";
  import type { Role } from "$lib/optima-api/modules/roles";
  import type { PermissionsCategorized } from "$lib/optima-api/modules/permissions";
  import { formatDate } from "$lib/utils";
  import { positionMenu } from "$lib/actions";
  import EditUserModal from "../../../components/EditUserModal.svelte";
  import AccessDenied from "../../../components/AccessDenied.svelte";
  import DeleteConfirmDialog from "../../../components/DeleteConfirmDialog.svelte";
  import "../../../styles/admin/users.css";

  type UserWithRoles = User & { roleDetails: Role[] };

  export let data: {
    permissions: PermissionMap;
    users: UserWithRoles[];
    roles: Role[];
    permissionNodes: PermissionsCategorized;
  };

  $: hasAccess = data.permissions["admin.users.view"] === true;
  $: canEdit = data.permissions["admin.users.edit"] === true;
  $: canDelete = data.permissions["admin.users.delete"] === true;
  $: canEditRoles = data.permissions["user.roles.other"] === true;
  $: canEditPermissions = data.permissions["user.permissions.other"] === true;
  $: users = data.users;
  $: allRoles = data.roles;

  function fullName(user: UserWithRoles): string {
    const computed = `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim();
    return computed || user.name || user.login || user.email;
  }

  // Search / filter
  let searchQuery = "";
  $: filteredUsers = users.filter((u) => {
    if (!searchQuery.trim()) return true;
    const q = searchQuery.toLowerCase();
    return (
      fullName(u).toLowerCase().includes(q) ||
      u.email.toLowerCase().includes(q) ||
      u.login.toLowerCase().includes(q)
    );
  });

  // Expanded row state
  let expandedUserId: string | null = null;

  function toggleUser(id: string) {
    expandedUserId = expandedUserId === id ? null : id;
  }

  // Three-dot menu
  let openMenuId: string | null = null;

  function toggleMenu(id: string) {
    openMenuId = openMenuId === id ? null : id;
  }

  // Edit modal state
  let editingUser: UserWithRoles | null = null;

  function openEdit(u: UserWithRoles) {
    editingUser = u;
    openMenuId = null;
  }

  function cancelEdit() {
    editingUser = null;
  }

  // Delete confirmation
  let userToDelete: UserWithRoles | null = null;
  let isDeleting = false;
  let deleteError = "";

  function openDeleteConfirm(u: UserWithRoles) {
    userToDelete = u;
    openMenuId = null;
  }

  function cancelDelete() {
    userToDelete = null;
    deleteError = "";
  }

  const handleDeleteEnhance: SubmitFunction = () => {
    isDeleting = true;
    deleteError = "";
    return async ({ result, update }) => {
      isDeleting = false;
      if (result.type === "success") {
        userToDelete = null;
      } else if (result.type === "failure") {
        deleteError =
          (result.data as { message?: string })?.message ??
          "Failed to delete user.";
      }
      await update();
    };
  };

  function initials(name: string): string {
    return name
      .split(" ")
      .map((n) => n[0])
      .join("")
      .slice(0, 2)
      .toUpperCase();
  }
</script>

<svelte:window on:click={() => (openMenuId = null)} />

{#if !hasAccess}
  <AccessDenied
    message="You don't have permission to manage users. Contact your administrator to request access."
  />
{:else if users.length === 0}
  <div class="admin-tab-empty">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
      <circle cx="9" cy="7" r="4" />
      <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
      <path d="M16 3.13a4 4 0 0 1 0 7.75" />
    </svg>
    <h3>No Users Found</h3>
    <p>There are no users in the system yet.</p>
  </div>
{:else}
  <!-- Edit user modal -->
  {#if editingUser}
    <EditUserModal
      user={editingUser}
      {allRoles}
      permissionNodes={data.permissionNodes}
      {canEditRoles}
      {canEditPermissions}
      onClose={cancelEdit}
      onSuccess={cancelEdit}
    />
  {/if}

  <!-- Delete confirmation dialog -->
  <DeleteConfirmDialog
    isOpen={!!userToDelete}
    title="Delete User"
    idValue={userToDelete?.id ?? ""}
    formAction="?/deleteUser"
    confirmLabel="Delete User"
    {isDeleting}
    error={deleteError}
    onCancel={cancelDelete}
    handleEnhance={handleDeleteEnhance}
  >
    Are you sure you want to delete <strong
      >{userToDelete ? fullName(userToDelete) : "this user"}</strong
    >? This action cannot be undone.
  </DeleteConfirmDialog>

  <div class="admin-table-header">
    <h3>
      Users
      <span class="result-count"
        >{filteredUsers.length} user{filteredUsers.length === 1
          ? ""
          : "s"}{#if searchQuery.trim()}
          &nbsp;(filtered){/if}</span
      >
    </h3>
    <div class="user-search-wrap">
      <svg
        class="user-search-icon"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        width="14"
        height="14"
      >
        <circle cx="11" cy="11" r="8" />
        <line x1="21" y1="21" x2="16.65" y2="16.65" />
      </svg>
      <input
        type="text"
        class="user-search-input"
        placeholder="Search users…"
        bind:value={searchQuery}
      />
    </div>
  </div>

  <div class="admin-table-wrap">
    <table class="admin-table">
      <thead>
        <tr>
          <th>User</th>
          <th>Email</th>
          <th>Login</th>
          <th>Roles</th>
          <th>Created</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        {#each filteredUsers as user (user.id)}
          <tr
            class="user-row"
            class:expanded={expandedUserId === user.id}
            on:click={() => toggleUser(user.id)}
          >
            <td>
              <div class="user-name-cell">
                {#if user.image}
                  <img
                    src={user.image}
                    alt={fullName(user)}
                    class="user-table-avatar"
                  />
                {:else}
                  <div class="user-table-avatar user-table-avatar-initials">
                    {initials(fullName(user))}
                  </div>
                {/if}
                <span class="user-table-name">{fullName(user)}</span>
              </div>
            </td>
            <td>
              <EmailText email={user.email} />
            </td>
            <td>
              <span class="user-login-mono">{user.login}</span>
            </td>
            <td>
              <span class="user-role-count">
                {user.roleDetails.length} role{user.roleDetails.length === 1
                  ? ""
                  : "s"}
              </span>
            </td>
            <td>{formatDate(user.createdAt)}</td>
            <td class="row-end-cell">
              <div class="row-end-content">
                {#if canEdit || canDelete}
                  <div class="menu-wrap">
                    <button
                      type="button"
                      class="menu-btn"
                      aria-label="User actions"
                      on:click|stopPropagation={() => toggleMenu(user.id)}
                    >
                      <svg
                        viewBox="0 0 16 16"
                        fill="currentColor"
                        width="14"
                        height="14"
                      >
                        <circle cx="8" cy="2.5" r="1.5" />
                        <circle cx="8" cy="8" r="1.5" />
                        <circle cx="8" cy="13.5" r="1.5" />
                      </svg>
                    </button>
                    {#if openMenuId === user.id}
                      <div class="user-menu" use:positionMenu>
                        {#if canEdit}
                          <button
                            type="button"
                            class="user-menu-item"
                            on:click|stopPropagation={() => openEdit(user)}
                          >
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="13"
                              height="13"
                            >
                              <path
                                d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"
                              />
                              <path
                                d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"
                              />
                            </svg>
                            Edit
                          </button>
                        {/if}
                        {#if canEdit && canDelete}
                          <div class="user-menu-sep"></div>
                        {/if}
                        {#if canDelete}
                          <button
                            type="button"
                            class="user-menu-item user-menu-item-danger"
                            on:click|stopPropagation={() =>
                              openDeleteConfirm(user)}
                          >
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="13"
                              height="13"
                            >
                              <polyline points="3 6 5 6 21 6" />
                              <path
                                d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"
                              />
                              <path d="M10 11v6M14 11v6" />
                              <path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" />
                            </svg>
                            Delete
                          </button>
                        {/if}
                      </div>
                    {/if}
                  </div>
                {/if}
                <svg
                  class="row-chevron"
                  class:open={expandedUserId === user.id}
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  width="16"
                  height="16"
                >
                  <path d="M6 9l6 6 6-6" />
                </svg>
              </div>
            </td>
          </tr>

          {#if expandedUserId === user.id}
            <tr class="user-detail-row">
              <td colspan="6">
                <div class="user-detail-content">
                  <div class="user-detail-grid">
                    <!-- User info section -->
                    <div class="user-detail-section">
                      <h4 class="user-detail-heading">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" />
                          <circle cx="12" cy="7" r="4" />
                        </svg>
                        Details
                      </h4>
                      <div class="user-detail-fields">
                        <div class="user-detail-field">
                          <span class="detail-label">ID</span>
                          <span class="detail-value detail-mono">{user.id}</span
                          >
                        </div>
                        <div class="user-detail-field">
                          <span class="detail-label">Email</span>
                          <span class="detail-value">
                            <EmailText email={user.email} />
                          </span>
                        </div>
                        <div class="user-detail-field">
                          <span class="detail-label">Login</span>
                          <span class="detail-value detail-mono"
                            >{user.login}</span
                          >
                        </div>
                        <div class="user-detail-field">
                          <span class="detail-label">Created</span>
                          <span class="detail-value"
                            >{formatDate(user.createdAt)}</span
                          >
                        </div>
                        <div class="user-detail-field">
                          <span class="detail-label">Updated</span>
                          <span class="detail-value"
                            >{formatDate(user.updatedAt)}</span
                          >
                        </div>
                      </div>
                    </div>

                    <!-- Roles section -->
                    <div class="user-detail-section">
                      <h4 class="user-detail-heading">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <path
                            d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"
                          />
                        </svg>
                        Roles
                        <span class="detail-count"
                          >{user.roleDetails.length}</span
                        >
                      </h4>
                      {#if user.roleDetails.length === 0}
                        <p class="user-detail-empty">No roles assigned</p>
                      {:else}
                        <div class="user-role-list">
                          {#each user.roleDetails as role (role.id)}
                            <div class="user-role-card">
                              <div class="user-role-card-header">
                                <svg
                                  viewBox="0 0 24 24"
                                  fill="none"
                                  stroke="currentColor"
                                  stroke-width="2"
                                  width="14"
                                  height="14"
                                >
                                  <path
                                    d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"
                                  />
                                </svg>
                                <span class="user-role-title">{role.title}</span
                                >
                                <span class="user-role-moniker"
                                  >{role.moniker}</span
                                >
                              </div>
                              {#if role.permissions.length > 0}
                                <div class="permission-tags">
                                  {#each role.permissions.slice(0, 8) as perm}
                                    <span class="permission-tag">{perm}</span>
                                  {/each}
                                  {#if role.permissions.length > 8}
                                    <span
                                      class="permission-tag permission-tag-more"
                                      >+{role.permissions.length - 8} more</span
                                    >
                                  {/if}
                                </div>
                              {/if}
                            </div>
                          {/each}
                        </div>
                      {/if}
                    </div>

                    <!-- Additional Permissions section -->
                    <div class="user-detail-section">
                      <h4 class="user-detail-heading">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <path d="M9 12l2 2 4-4" />
                          <path
                            d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"
                          />
                        </svg>
                        Additional Permissions
                        {#if user.permissions?.length}
                          <span class="detail-count"
                            >{user.permissions.length}</span
                          >
                        {/if}
                      </h4>
                      {#if !user.permissions?.length}
                        <p class="user-detail-empty">
                          No additional permissions assigned
                        </p>
                      {:else}
                        <div class="permission-tags">
                          {#each user.permissions as perm}
                            <span class="permission-tag">{perm}</span>
                          {/each}
                        </div>
                      {/if}
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          {/if}
        {/each}
      </tbody>
    </table>
  </div>

  {#if filteredUsers.length === 0 && searchQuery.trim()}
    <div class="admin-tab-empty">
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
      >
        <circle cx="11" cy="11" r="8" />
        <line x1="21" y1="21" x2="16.65" y2="16.65" />
      </svg>
      <h3>No Results</h3>
      <p>No users match &ldquo;{searchQuery}&rdquo;. Try a different search.</p>
    </div>
  {/if}
{/if}
