<script setup lang="ts">
import {
  Loader2,
  Plus,
  ShieldCheck,
  UsersRound,
  X,
} from "@lucide/vue";
import { computed, onMounted, reactive, ref } from "vue";

import { ApiError } from "../api/http";
import { createUser, listUsers } from "../api/auth";
import type { UserRecord, UserRole } from "../api/types";
import StatCard from "../components/StatCard.vue";

const users = ref<UserRecord[]>([]);
const loading = ref(false);
const saving = ref(false);
const errorMessage = ref("");
const successMessage = ref("");
const showUserModal = ref(false);

const form = reactive({
  username: "",
  display_name: "",
  email: "",
  phone: "",
  department: "",
  position_title: "",
  password: "",
  role: "viewer" as UserRole,
});

const superuserCount = computed(() => users.value.filter((user) => user.role === "superuser").length);
const managerCount = computed(() => users.value.filter((user) => user.role === "manager").length);
const viewerCount = computed(() => users.value.filter((user) => user.role === "viewer").length);

onMounted(loadUsers);

async function loadUsers(): Promise<void> {
  loading.value = true;
  errorMessage.value = "";
  try {
    users.value = await listUsers();
  } catch (error) {
    errorMessage.value = error instanceof ApiError ? error.message : "用户列表加载失败";
  } finally {
    loading.value = false;
  }
}

async function submit(): Promise<void> {
  saving.value = true;
  errorMessage.value = "";
  successMessage.value = "";

  try {
    const user = await createUser({
      username: form.username.trim(),
      display_name: form.display_name.trim(),
      email: form.email.trim(),
      phone: form.phone.trim(),
      department: form.department.trim(),
      position_title: form.position_title.trim(),
      password: form.password,
      role: form.role,
    });
    users.value = [user, ...users.value.filter((item) => item.id !== user.id)];
    resetForm();
    showUserModal.value = false;
    successMessage.value = "用户已创建";
  } catch (error) {
    errorMessage.value = error instanceof ApiError ? error.message : "用户创建失败";
  } finally {
    saving.value = false;
  }
}

function resetForm(): void {
  Object.assign(form, {
    username: "",
    display_name: "",
    email: "",
    phone: "",
    department: "",
    position_title: "",
    password: "",
    role: "viewer",
  });
}

function openCreateModal(): void {
  errorMessage.value = "";
  successMessage.value = "";
  resetForm();
  showUserModal.value = true;
}

function closeUserModal(): void {
  showUserModal.value = false;
  errorMessage.value = "";
  resetForm();
}

function roleLabel(role: string): string {
  const labels: Record<string, string> = {
    superuser: "超级用户",
    manager: "管理者",
    viewer: "查看权限",
  };
  return labels[role] || role;
}
</script>

<template>
  <div class="view-stack users-page">
    <header class="page-header">
      <div>
        <h1>用户管理</h1>
        <p>账号、角色与菜单权限。</p>
      </div>
    </header>

    <section class="summary-strip">
      <StatCard title="超级用户" :value="String(superuserCount)" :icon="ShieldCheck" tone="blue" meta="全部权限" />
      <StatCard title="管理者" :value="String(managerCount)" :icon="UsersRound" tone="green" meta="计算权限" />
      <StatCard title="查看权限" :value="String(viewerCount)" :icon="UsersRound" tone="neutral" meta="只读权限" />
    </section>

    <p v-if="errorMessage && !showUserModal" class="form-error">{{ errorMessage }}</p>
    <p v-if="successMessage" class="form-success">{{ successMessage }}</p>

    <section class="panel table-panel user-list-panel">
      <div class="panel-header user-list-header">
        <div>
          <h2>用户列表</h2>
          <p>{{ users.length }} 个账号</p>
        </div>
        <button class="primary-button" type="button" @click="openCreateModal">
          <Plus :size="18" aria-hidden="true" />
          <span>新增用户</span>
        </button>
      </div>
      <div class="table-wrap">
        <table class="data-table">
          <thead>
            <tr>
              <th>用户名</th>
              <th>显示名称</th>
              <th>联系方式</th>
              <th>部门/职位</th>
              <th>角色</th>
              <th>状态</th>
              <th>菜单</th>
              <th>创建时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.id">
              <td>
                <strong>{{ user.username }}</strong>
                <span>ID {{ user.id }}</span>
              </td>
              <td>{{ user.display_name || "-" }}</td>
              <td>
                <strong>{{ user.email || "-" }}</strong>
                <span>{{ user.phone || "-" }}</span>
              </td>
              <td>
                <strong>{{ user.department || "-" }}</strong>
                <span>{{ user.position_title || "-" }}</span>
              </td>
              <td><span class="status-chip neutral">{{ roleLabel(user.role) }}</span></td>
              <td>
                <span class="status-chip" :class="user.is_active ? 'green' : 'red'">
                  {{ user.is_active ? "启用" : "停用" }}
                </span>
              </td>
              <td>{{ user.menus.map((menu) => menu.name).join("、") || "-" }}</td>
              <td>{{ new Date(user.created_at).toLocaleString() }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div v-if="!users.length && !loading" class="empty-state">
        <p>暂无用户</p>
      </div>
    </section>

    <Teleport to="body">
      <div v-if="showUserModal" class="modal-backdrop user-modal-backdrop" @click.self="closeUserModal">
        <section class="profile-modal user-modal" aria-label="用户维护">
          <div class="modal-header">
            <div>
              <h2>新增用户</h2>
              <p>角色决定可见菜单和操作权限</p>
            </div>
            <button class="icon-button" type="button" title="关闭" @click="closeUserModal">
              <X :size="21" aria-hidden="true" />
            </button>
          </div>

          <form class="user-modal-form" @submit.prevent="submit">
            <div class="user-modal-fields">
              <label class="field">
                <span>用户名</span>
                <input v-model="form.username" required minlength="2" type="text" />
              </label>
              <label class="field">
                <span>显示名称</span>
                <input v-model="form.display_name" type="text" />
              </label>
              <label class="field">
                <span>初始密码</span>
                <input v-model="form.password" required minlength="6" type="password" />
              </label>
              <label class="field">
                <span>角色</span>
                <select v-model="form.role">
                  <option value="viewer">查看权限</option>
                  <option value="manager">管理者</option>
                  <option value="superuser">超级用户</option>
                </select>
              </label>
              <label class="field">
                <span>邮箱</span>
                <input v-model="form.email" type="email" />
              </label>
              <label class="field">
                <span>手机号</span>
                <input v-model="form.phone" type="tel" />
              </label>
              <label class="field">
                <span>部门</span>
                <input v-model="form.department" type="text" />
              </label>
              <label class="field">
                <span>职位</span>
                <input v-model="form.position_title" type="text" />
              </label>
              <p v-if="errorMessage" class="form-error user-modal-message">{{ errorMessage }}</p>
              <div class="form-actions user-modal-actions">
                <button class="secondary-button" type="button" @click="resetForm">清空</button>
                <button class="secondary-button" type="button" @click="closeUserModal">取消</button>
                <button class="primary-button" type="submit" :disabled="saving">
                  <Loader2 v-if="saving" class="spin" :size="18" aria-hidden="true" />
                  <Plus v-else :size="18" aria-hidden="true" />
                  <span>{{ saving ? "创建中" : "创建用户" }}</span>
                </button>
              </div>
            </div>
          </form>
        </section>
      </div>
    </Teleport>
  </div>
</template>
