<script setup lang="ts">
import { computed, onMounted } from "vue";
import DataTable from "@/components/common/DataTable.vue";
import type { DataTableColumn } from "@/components/common/DataTable.vue";
import EmptyState from "@/components/common/EmptyState.vue";
import LoadingState from "@/components/common/LoadingState.vue";
import TablePageLayout from "@/components/layout/TablePageLayout.vue";
import { useAccessStore } from "@/stores/access";
import { accessUserLabel, type AccessUserRow } from "@/stores/admin-access-view";
import type { AccessUserRole, AccessUserStatus } from "@/types";

const access = useAccessStore();
const columns: DataTableColumn[] = [
  { key: "user", label: "用户" },
  { key: "role", label: "角色" },
  { key: "status", label: "状态" },
  { key: "tools", label: "工具" },
  { key: "tuples", label: "Tuples", align: "right" },
  { key: "actions", label: "操作", align: "right" }
];

const openfga = computed(() => access.summaryView.openfga);

onMounted(() => void access.refresh());

function selectRow(row: AccessUserRow): void {
  void access.selectUser(row.id);
}

function onRoleChange(event: Event): void {
  const role = (event.target as HTMLSelectElement | null)?.value as AccessUserRole | undefined;
  if (role) void access.updateSelectedUser({ role });
}

function onStatusChange(event: Event): void {
  const status = (event.target as HTMLSelectElement | null)?.value as AccessUserStatus | undefined;
  if (status) void access.updateSelectedUser({ status });
}

function onToolChange(toolId: string, event: Event): void {
  const checked = (event.target as HTMLInputElement | null)?.checked === true;
  void access.setTool(toolId, checked);
}

function rowKey(row: AccessUserRow): string {
  return row.id;
}

function valueText(value: unknown): string {
  if (typeof value === "boolean") return value ? "yes" : "no";
  if (typeof value === "number") return String(value);
  if (typeof value === "string" && value.trim()) return value;
  return "-";
}
</script>

<template>
  <section class="route-stack access-admin-page">
    <LoadingState v-if="access.loading && !access.userRows.length" />
    <EmptyState v-else-if="access.error" title="Access 加载失败" :description="access.error" action-label="重试" @action="access.refresh" />
    <template v-else>
      <div class="overview-grid access-summary-grid">
        <article class="metric-card">
          <span>Users</span>
          <strong>{{ access.summaryView.users }}</strong>
        </article>
        <article class="metric-card">
          <span>Tuples</span>
          <strong>{{ access.summaryView.tuples }}</strong>
        </article>
        <article class="metric-card">
          <span>Tool grants</span>
          <strong>{{ access.summaryView.toolTuples }}</strong>
        </article>
      </div>

      <section id="access-openfga-panel" class="data-panel admin-crud-panel openfga-panel">
        <header class="panel-header">
          <h2>OpenFGA</h2>
          <span class="status-pill" :data-status="valueText(openfga.status || (openfga.ready ? 'active' : 'disabled'))">{{ valueText(openfga.status || (openfga.ready ? 'ready' : 'not ready')) }}</span>
        </header>
        <dl class="field-grid">
          <div><dt>mode</dt><dd>{{ valueText(openfga.mode) }}</dd></div>
          <div><dt>store</dt><dd>{{ valueText(openfga.storeName || openfga.storeId) }}</dd></div>
          <div><dt>model</dt><dd>{{ valueText(openfga.modelId) }}</dd></div>
          <div><dt>values</dt><dd>{{ openfga.valuesRedacted === false ? "visible" : "redacted" }}</dd></div>
        </dl>
      </section>

      <TablePageLayout title="Access users" subtitle="Cloud API 同源 admin access matrix">
        <template #actions>
          <button id="access-refresh" class="table-action" type="button" :disabled="access.loading" @click="access.refresh">刷新</button>
        </template>
        <DataTable :columns="columns" :rows="access.userRows" :row-key="rowKey" empty-text="暂无用户记录。">
          <template #cell-user="{ row }">
            <button class="link-button" type="button" :data-selected="row.id === access.selectedUserId" @click="selectRow(row as AccessUserRow)">
              <strong>{{ accessUserLabel(row as AccessUserRow) }}</strong>
              <small>{{ (row as AccessUserRow).username || (row as AccessUserRow).id }}</small>
            </button>
          </template>
          <template #cell-role="{ row }">
            <span class="status-pill" :data-status="(row as AccessUserRow).role">{{ (row as AccessUserRow).role }}</span>
          </template>
          <template #cell-status="{ row }">
            <span class="status-pill" :data-status="(row as AccessUserRow).status">{{ (row as AccessUserRow).status }}</span>
          </template>
          <template #cell-tools="{ row }">
            {{ (row as AccessUserRow).toolCount }} / {{ Object.keys((row as AccessUserRow).tools).length }}
          </template>
          <template #cell-tuples="{ row }">
            {{ (row as AccessUserRow).tupleCount }}
          </template>
          <template #cell-actions="{ row }">
            <button class="table-action" type="button" @click="selectRow(row as AccessUserRow)">详情</button>
          </template>
        </DataTable>
      </TablePageLayout>

      <section id="access-user-detail" class="data-panel admin-crud-panel access-detail-panel">
        <header class="panel-header">
          <div>
            <h2>Selected user</h2>
            <small>{{ access.selectedUser ? access.selectedUser.id : "未选择" }}</small>
          </div>
          <span v-if="access.detailLoading" class="status-pill">loading</span>
        </header>
        <p v-if="access.mutationError" class="form-error">{{ access.mutationError }}</p>
        <EmptyState v-if="!access.selectedUser" title="请选择用户" description="从 Access users 表格选择一个用户以编辑 role/status 和 tool matrix。" />
        <template v-else>
          <div class="access-user-head">
            <strong>{{ accessUserLabel(access.selectedUser) }}</strong>
            <small>{{ access.selectedUser.username || access.selectedUser.id }}</small>
          </div>
          <div class="form-grid compact-form-grid">
            <label>
              <span>Role</span>
              <select id="access-role-select" :value="access.selectedUser.role" :disabled="access.savingKey !== null" @change="onRoleChange">
                <option value="admin">admin</option>
                <option value="member">member</option>
                <option value="viewer">viewer</option>
              </select>
            </label>
            <label>
              <span>Status</span>
              <select id="access-status-select" :value="access.selectedUser.status" :disabled="access.savingKey !== null" @change="onStatusChange">
                <option value="active">active</option>
                <option value="disabled">disabled</option>
                <option value="pending">pending</option>
              </select>
            </label>
          </div>
          <div class="tool-toggle-grid">
            <label v-for="tool in access.toolRows" :key="tool.id" class="tool-toggle-row" data-access-tool-toggle>
              <span>
                <strong>{{ tool.label }}</strong>
                <small>{{ tool.id }}</small>
              </span>
              <input type="checkbox" :checked="tool.allowed" :disabled="access.savingKey !== null" @change="onToolChange(tool.id, $event)">
            </label>
          </div>
          <div class="tuple-list">
            <h3>Tuples</h3>
            <p v-if="!access.detailView.tuples.length" class="muted-box">暂无 tuple。</p>
            <ul v-else>
              <li v-for="tuple in access.detailView.tuples" :key="String(tuple.object || tuple.relation || tuple.userId)">
                <code>{{ valueText(tuple.userId) }}</code>
                <span>{{ valueText(tuple.relation) }}</span>
                <code>{{ valueText(tuple.object) }}</code>
              </li>
            </ul>
          </div>
        </template>
      </section>
    </template>
  </section>
</template>
