<script lang="ts">
  import type { SubmitFunction } from "@sveltejs/kit";
  import type { PermissionMap } from "$lib/permissions";
  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 CreateRoleModal from "../../../components/CreateRoleModal.svelte";
  import AccessDenied from "../../../components/AccessDenied.svelte";
  import DeleteConfirmDialog from "../../../components/DeleteConfirmDialog.svelte";
  import "../../../styles/admin/roles.css";

  interface RoleUser {
    id: string;
    name: string;
    login: string;
    roles: string[];
    createdAt: string;
    updatedAt: string;
  }

  type RoleWithUsers = Role & { users: RoleUser[] };

  export let data: {
    permissions: PermissionMap;
    roles: RoleWithUsers[];
    permissionNodes: PermissionsCategorized;
  };

  $: hasAccess = data.permissions["admin.roles.view"] === true;
  $: canCreate = data.permissions["admin.roles.create"] === true;
  $: canEdit = data.permissions["admin.roles.edit"] === true;
  $: canDelete = data.permissions["admin.roles.delete"] === true;
  $: roles = data.roles;

  // Create/edit modal state
  let isCreateModalOpen = false;
  let roleToEdit: Role | null = null;

  function openEdit(r: Role) {
    roleToEdit = r;
    isCreateModalOpen = true;
    openMenuId = null;
  }

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

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

  // Delete confirmation
  let roleToDelete: Role | null = null;
  let isDeleting = false;
  let deleteError = "";

  function openDeleteConfirm(r: Role) {
    roleToDelete = r;
    openMenuId = null;
  }

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

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

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

  function toggleRole(id: string) {
    expandedRoleId = expandedRoleId === id ? null : id;
  }
</script>

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

{#if !hasAccess}
  <AccessDenied
    message="You don't have permission to manage roles. Contact your administrator to request access."
  />
{:else if roles.length === 0}
  <CreateRoleModal
    isOpen={isCreateModalOpen}
    permissionNodes={data.permissionNodes}
    {roleToEdit}
    onClose={() => {
      isCreateModalOpen = false;
      roleToEdit = null;
    }}
    onSuccess={() => {
      isCreateModalOpen = false;
      roleToEdit = null;
    }}
  />
  <div class="admin-tab-empty">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
    </svg>
    <h3>No Roles Found</h3>
    <p>
      There are no roles configured yet. Create your first role to get started.
    </p>
    {#if canCreate}
      <button
        type="button"
        class="create-role-btn"
        on:click={() => (isCreateModalOpen = true)}
      >
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          width="14"
          height="14"
        >
          <line x1="12" y1="5" x2="12" y2="19" />
          <line x1="5" y1="12" x2="19" y2="12" />
        </svg>
        Create Role
      </button>
    {/if}
  </div>
{:else}
  <CreateRoleModal
    isOpen={isCreateModalOpen}
    permissionNodes={data.permissionNodes}
    {roleToEdit}
    onClose={() => {
      isCreateModalOpen = false;
      roleToEdit = null;
    }}
    onSuccess={() => {
      isCreateModalOpen = false;
      roleToEdit = null;
    }}
  />

  <DeleteConfirmDialog
    isOpen={!!roleToDelete}
    title="Delete Role"
    idValue={roleToDelete?.id ?? ""}
    formAction="?/deleteRole"
    confirmLabel="Delete Role"
    {isDeleting}
    error={deleteError}
    onCancel={cancelDelete}
    handleEnhance={handleDeleteEnhance}
  >
    Are you sure you want to delete <strong>{roleToDelete?.title}</strong>? This
    action cannot be undone.
  </DeleteConfirmDialog>

  <div class="admin-table-header">
    <h3>
      Roles
      <span class="result-count"
        >{roles.length} role{roles.length === 1 ? "" : "s"}</span
      >
    </h3>
    {#if canCreate}
      <button
        type="button"
        class="create-role-btn"
        on:click={() => (isCreateModalOpen = true)}
      >
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          width="14"
          height="14"
        >
          <line x1="12" y1="5" x2="12" y2="19" />
          <line x1="5" y1="12" x2="19" y2="12" />
        </svg>
        Create Role
      </button>
    {/if}
  </div>

  <div class="admin-table-wrap">
    <table class="admin-table">
      <thead>
        <tr>
          <th>Title</th>
          <th>Moniker</th>
          <th>Permissions</th>
          <th>Users</th>
          <th>Created</th>
          <th>Updated</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        {#each roles as role (role.id)}
          <tr
            class="role-row"
            class:expanded={expandedRoleId === role.id}
            on:click={() => toggleRole(role.id)}
          >
            <td>
              <div class="role-title-cell">
                <svg
                  class="role-icon"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
                </svg>
                <span class="role-title">{role.title}</span>
              </div>
            </td>
            <td>
              <span class="role-moniker">{role.moniker}</span>
            </td>
            <td>
              <span class="role-perm-count">
                {role.permissions.length} permission{role.permissions.length ===
                1
                  ? ""
                  : "s"}
              </span>
            </td>
            <td>
              <span class="role-user-count">
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  width="13"
                  height="13"
                >
                  <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" />
                  <circle cx="9" cy="7" r="4" />
                  <path d="M23 21v-2a4 4 0 00-3-3.87" />
                  <path d="M16 3.13a4 4 0 010 7.75" />
                </svg>
                {role.users.length} user{role.users.length === 1 ? "" : "s"}
              </span>
            </td>
            <td>{formatDate(role.createdAt)}</td>
            <td>{formatDate(role.updatedAt)}</td>
            <td class="row-end-cell">
              <div class="row-end-content">
                {#if role.moniker === "administrator"}
                  <span class="system-badge">
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="11"
                      height="11"
                    >
                      <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                      <path d="M7 11V7a5 5 0 0110 0v4" />
                    </svg>
                    System
                  </span>
                {:else if canEdit || canDelete}
                  <div class="menu-wrap">
                    <button
                      type="button"
                      class="menu-btn"
                      aria-label="Role actions"
                      on:click|stopPropagation={() => toggleMenu(role.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 === role.id}
                      <div class="role-menu" use:positionMenu>
                        {#if canEdit}
                          <button
                            type="button"
                            class="role-menu-item"
                            on:click|stopPropagation={() => openEdit(role)}
                          >
                            <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="role-menu-sep"></div>
                        {/if}
                        {#if canDelete}
                          <button
                            type="button"
                            class="role-menu-item role-menu-item-danger"
                            on:click|stopPropagation={() =>
                              openDeleteConfirm(role)}
                          >
                            <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={expandedRoleId === role.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 expandedRoleId === role.id}
            <tr class="role-detail-row">
              <td colspan="7">
                <div class="role-detail-content">
                  <div class="role-detail-grid">
                    <div class="role-detail-section">
                      <h4 class="role-detail-heading">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <path
                            d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"
                          />
                          <rect x="9" y="3" width="6" height="4" rx="1" />
                        </svg>
                        Permissions
                        <span class="detail-count"
                          >{role.permissions.length}</span
                        >
                      </h4>
                      {#if role.permissions.length === 0}
                        <p class="role-detail-empty">No permissions assigned</p>
                      {:else}
                        <div class="permission-tags">
                          {#each role.permissions as perm}
                            <span class="permission-tag">{perm}</span>
                          {/each}
                        </div>
                      {/if}
                    </div>

                    <div class="role-detail-section">
                      <h4 class="role-detail-heading">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" />
                          <circle cx="9" cy="7" r="4" />
                          <path d="M23 21v-2a4 4 0 00-3-3.87" />
                          <path d="M16 3.13a4 4 0 010 7.75" />
                        </svg>
                        Users
                        <span class="detail-count">{role.users.length}</span>
                      </h4>
                      {#if role.users.length === 0}
                        <p class="role-detail-empty">
                          No users assigned to this role
                        </p>
                      {:else}
                        <div class="user-list">
                          {#each role.users as user (user.id)}
                            <div class="user-card">
                              <div class="user-avatar">
                                {user.name
                                  .split(" ")
                                  .map((n) => n[0])
                                  .join("")
                                  .slice(0, 2)
                                  .toUpperCase()}
                              </div>
                              <div class="user-info">
                                <span class="user-name">{user.name}</span>
                                <span class="user-login">{user.login}</span>
                              </div>
                            </div>
                          {/each}
                        </div>
                      {/if}
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          {/if}
        {/each}
      </tbody>
    </table>
  </div>
{/if}
