<script lang="ts">
  import type { SubmitFunction } from "@sveltejs/kit";
  import type { PermissionMap } from "$lib/permissions";
  import type {
    CredentialType,
    CredentialTypeField,
  } from "$lib/optima-api/modules/credentialTypes";
  import { formatDate } from "$lib/utils";
  import { positionMenu } from "$lib/actions";
  import CreateCredentialTypeModal from "../../../components/CreateCredentialTypeModal.svelte";
  import AccessDenied from "../../../components/AccessDenied.svelte";
  import DeleteConfirmDialog from "../../../components/DeleteConfirmDialog.svelte";
  import "../../../styles/admin/credential-types.css";

  export let data: {
    permissions: PermissionMap;
    credentialTypes: CredentialType[];
    valueTypes: string[];
  };

  $: hasAccess = data.permissions["admin.credential-types.view"] === true;
  $: canCreate = data.permissions["admin.credential-types.create"] === true;
  $: canEdit = data.permissions["admin.credential-types.edit"] === true;
  $: canDelete = data.permissions["admin.credential-types.delete"] === true;
  $: credentialTypes = data.credentialTypes;
  $: valueTypes = data.valueTypes ?? [];

  // Search / filter
  let searchQuery = "";
  $: filteredTypes = credentialTypes.filter((ct) => {
    if (!searchQuery.trim()) return true;
    const q = searchQuery.toLowerCase();
    return (
      ct.name.toLowerCase().includes(q) ||
      ct.permissionScope.toLowerCase().includes(q)
    );
  });

  // Create / edit modal state
  let isCreateModalOpen = false;
  let typeToEdit: CredentialType | null = null;

  function openEdit(ct: CredentialType) {
    typeToEdit = ct;
    isCreateModalOpen = true;
    openMenuId = null;
  }

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

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

  // Delete confirmation
  let typeToDelete: CredentialType | null = null;
  let isDeleting = false;
  let deleteError = "";

  function openDeleteConfirm(ct: CredentialType) {
    typeToDelete = ct;
    openMenuId = null;
  }

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

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

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

  function toggleType(id: string) {
    expandedTypeId = expandedTypeId === id ? null : id;
  }

  function valueTypeLabel(vt: string): string {
    return vt
      .split("_")
      .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
      .join(" ");
  }
</script>

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

{#if !hasAccess}
  <AccessDenied
    message="You don't have permission to manage credential types. Contact your administrator to request access."
  />
{:else if credentialTypes.length === 0}
  <CreateCredentialTypeModal
    isOpen={isCreateModalOpen}
    {typeToEdit}
    {valueTypes}
    onClose={() => {
      isCreateModalOpen = false;
      typeToEdit = null;
    }}
    onSuccess={() => {
      isCreateModalOpen = false;
      typeToEdit = null;
    }}
  />
  <div class="admin-tab-empty">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
      <path d="M7 11V7a5 5 0 0 1 10 0v4" />
    </svg>
    <h3>No Credential Types Found</h3>
    <p>
      There are no credential types configured yet. Create your first credential
      type to get started.
    </p>
    {#if canCreate}
      <button
        type="button"
        class="create-ct-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 Credential Type
      </button>
    {/if}
  </div>
{:else}
  <CreateCredentialTypeModal
    isOpen={isCreateModalOpen}
    {typeToEdit}
    {valueTypes}
    onClose={() => {
      isCreateModalOpen = false;
      typeToEdit = null;
    }}
    onSuccess={() => {
      isCreateModalOpen = false;
      typeToEdit = null;
    }}
  />

  <DeleteConfirmDialog
    isOpen={!!typeToDelete}
    title="Delete Credential Type"
    idValue={typeToDelete?.id ?? ""}
    formAction="?/deleteCredentialType"
    confirmLabel="Delete"
    {isDeleting}
    error={deleteError}
    onCancel={cancelDelete}
    handleEnhance={handleDeleteEnhance}
  >
    Are you sure you want to delete <strong>{typeToDelete?.name}</strong>?
    {#if typeToDelete && typeToDelete.credentialCount > 0}
      This type has <strong>{typeToDelete.credentialCount}</strong>
      credential{typeToDelete.credentialCount === 1 ? "" : "s"} associated with it.
    {/if}
    This action cannot be undone.
  </DeleteConfirmDialog>

  <div class="admin-table-header">
    <h3>
      Credential Types
      <span class="result-count"
        >{filteredTypes.length} type{filteredTypes.length === 1
          ? ""
          : "s"}{#if searchQuery.trim()}&nbsp;(filtered){/if}</span
      >
    </h3>
    <div style="display:flex;align-items:center;gap:10px;">
      <div class="ct-search-wrap">
        <svg
          class="ct-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="ct-search-input"
          placeholder="Search types…"
          bind:value={searchQuery}
        />
      </div>
      {#if canCreate}
        <button
          type="button"
          class="create-ct-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 Type
        </button>
      {/if}
    </div>
  </div>

  <div class="admin-table-wrap">
    <table class="admin-table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Permission Scope</th>
          <th>Fields</th>
          <th>Credentials</th>
          <th>Created</th>
          <th>Updated</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        {#each filteredTypes as ct (ct.id)}
          <tr
            class="ct-row"
            class:expanded={expandedTypeId === ct.id}
            on:click={() => toggleType(ct.id)}
          >
            <td>
              <div class="ct-name-cell">
                <svg
                  class="ct-icon"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                  <path d="M7 11V7a5 5 0 0 1 10 0v4" />
                </svg>
                <span class="ct-name">{ct.name}</span>
              </div>
            </td>
            <td>
              <span class="ct-scope">{ct.permissionScope}</span>
            </td>
            <td>
              <span class="ct-field-count">
                {ct.fields.length} field{ct.fields.length === 1 ? "" : "s"}
              </span>
            </td>
            <td>
              <span class="ct-cred-count">
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  width="13"
                  height="13"
                >
                  <path
                    d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"
                  />
                  <line x1="8" y1="12" x2="16" y2="12" />
                </svg>
                {ct.credentialCount} credential{ct.credentialCount === 1
                  ? ""
                  : "s"}
              </span>
            </td>
            <td>{formatDate(ct.createdAt)}</td>
            <td>{formatDate(ct.updatedAt)}</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="Credential type actions"
                      on:click|stopPropagation={() => toggleMenu(ct.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 === ct.id}
                      <div class="ct-menu" use:positionMenu>
                        {#if canEdit}
                          <button
                            type="button"
                            class="ct-menu-item"
                            on:click|stopPropagation={() => openEdit(ct)}
                          >
                            <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="ct-menu-sep"></div>
                        {/if}
                        {#if canDelete}
                          <button
                            type="button"
                            class="ct-menu-item ct-menu-item-danger"
                            on:click|stopPropagation={() =>
                              openDeleteConfirm(ct)}
                          >
                            <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={expandedTypeId === ct.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 expandedTypeId === ct.id}
            <tr class="ct-detail-row">
              <td colspan="7">
                <div class="ct-detail-content">
                  <div class="ct-detail-grid">
                    <!-- Info section -->
                    <div class="ct-detail-section">
                      <h4 class="ct-detail-heading">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <circle cx="12" cy="12" r="10" />
                          <line x1="12" y1="16" x2="12" y2="12" />
                          <line x1="12" y1="8" x2="12.01" y2="8" />
                        </svg>
                        Details
                      </h4>
                      <div class="ct-detail-fields">
                        <div class="ct-detail-field">
                          <span class="detail-label">ID</span>
                          <span class="detail-value detail-mono">{ct.id}</span>
                        </div>
                        <div class="ct-detail-field">
                          <span class="detail-label">Permission Scope</span>
                          <span class="detail-value detail-mono"
                            >{ct.permissionScope}</span
                          >
                        </div>
                        {#if ct.icon}
                          <div class="ct-detail-field">
                            <span class="detail-label">Icon</span>
                            <span class="detail-value">{ct.icon}</span>
                          </div>
                        {/if}
                        <div class="ct-detail-field">
                          <span class="detail-label">Credentials</span>
                          <span class="detail-value"
                            >{ct.credentialCount} credential{ct.credentialCount ===
                            1
                              ? ""
                              : "s"}</span
                          >
                        </div>
                        <div class="ct-detail-field">
                          <span class="detail-label">Created</span>
                          <span class="detail-value"
                            >{formatDate(ct.createdAt)}</span
                          >
                        </div>
                        <div class="ct-detail-field">
                          <span class="detail-label">Updated</span>
                          <span class="detail-value"
                            >{formatDate(ct.updatedAt)}</span
                          >
                        </div>
                      </div>
                    </div>

                    <!-- Fields section -->
                    <div class="ct-detail-section">
                      <h4 class="ct-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>
                        Fields
                        <span class="detail-count">{ct.fields.length}</span>
                      </h4>
                      {#if ct.fields.length === 0}
                        <p class="ct-detail-empty">No fields defined</p>
                      {:else}
                        <div class="ct-field-list">
                          {#each ct.fields as field (field.id)}
                            <div class="ct-field-card">
                              <div class="ct-field-icon">
                                {#if field.valueType === "multi_credential"}
                                  <svg
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="2"
                                    width="14"
                                    height="14"
                                  >
                                    <rect
                                      x="2"
                                      y="3"
                                      width="20"
                                      height="6"
                                      rx="1"
                                    />
                                    <rect
                                      x="2"
                                      y="15"
                                      width="20"
                                      height="6"
                                      rx="1"
                                    />
                                    <path d="M12 9v6" />
                                  </svg>
                                {:else if field.secure}
                                  <svg
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="2"
                                    width="14"
                                    height="14"
                                  >
                                    <rect
                                      x="3"
                                      y="11"
                                      width="18"
                                      height="11"
                                      rx="2"
                                      ry="2"
                                    />
                                    <path d="M7 11V7a5 5 0 0 1 10 0v4" />
                                  </svg>
                                {:else}
                                  <svg
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="2"
                                    width="14"
                                    height="14"
                                  >
                                    <polyline points="4 7 4 4 20 4 20 7" />
                                    <line x1="9" y1="20" x2="15" y2="20" />
                                    <line x1="12" y1="4" x2="12" y2="20" />
                                  </svg>
                                {/if}
                              </div>
                              <div class="ct-field-info">
                                <span class="ct-field-name">{field.name}</span>
                                <div class="ct-field-meta">
                                  <span>{valueTypeLabel(field.valueType)}</span>
                                  {#if field.required}
                                    <span class="ct-field-badge required"
                                      >Required</span
                                    >
                                  {/if}
                                  {#if field.secure}
                                    <span class="ct-field-badge secure"
                                      >Secure</span
                                    >
                                  {/if}
                                </div>
                              </div>
                            </div>
                            {#if field.valueType === "multi_credential" && field.subFields && field.subFields.length > 0}
                              <div class="ct-subfield-group">
                                <div class="ct-subfield-connector"></div>
                                <div class="ct-subfield-list">
                                  {#each field.subFields as subField (subField.id)}
                                    <div class="ct-field-card ct-subfield-card">
                                      <div
                                        class="ct-field-icon ct-subfield-icon"
                                      >
                                        {#if subField.secure}
                                          <svg
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            width="12"
                                            height="12"
                                          >
                                            <rect
                                              x="3"
                                              y="11"
                                              width="18"
                                              height="11"
                                              rx="2"
                                              ry="2"
                                            />
                                            <path
                                              d="M7 11V7a5 5 0 0 1 10 0v4"
                                            />
                                          </svg>
                                        {:else}
                                          <svg
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            width="12"
                                            height="12"
                                          >
                                            <polyline
                                              points="4 7 4 4 20 4 20 7"
                                            />
                                            <line
                                              x1="9"
                                              y1="20"
                                              x2="15"
                                              y2="20"
                                            />
                                            <line
                                              x1="12"
                                              y1="4"
                                              x2="12"
                                              y2="20"
                                            />
                                          </svg>
                                        {/if}
                                      </div>
                                      <div class="ct-field-info">
                                        <span class="ct-field-name"
                                          >{subField.name}</span
                                        >
                                        <div class="ct-field-meta">
                                          <span
                                            >{valueTypeLabel(
                                              subField.valueType,
                                            )}</span
                                          >
                                          {#if subField.required}
                                            <span
                                              class="ct-field-badge required"
                                              >Required</span
                                            >
                                          {/if}
                                          {#if subField.secure}
                                            <span class="ct-field-badge secure"
                                              >Secure</span
                                            >
                                          {/if}
                                        </div>
                                      </div>
                                    </div>
                                  {/each}
                                </div>
                              </div>
                            {/if}
                          {/each}
                        </div>
                      {/if}
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          {/if}
        {/each}
      </tbody>
    </table>
  </div>

  {#if filteredTypes.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 credential types match &ldquo;{searchQuery}&rdquo;. Try a different
        search.
      </p>
    </div>
  {/if}
{/if}
