<script setup lang="ts">
import { computed, onMounted, ref } from "vue";

import { api } from "../../shared/api/client";
import { useUiStore } from "../../shared/stores/ui";

type Membership = {
  status: string;
  active: boolean;
  is_permanent: boolean;
  expires_at: string | null;
  daily_limit: number;
};
type AccountMembership = { user_id: number; username: string; is_admin: boolean; membership: Membership };

const ui = useUiStore();
const accounts = ref<AccountMembership[]>([]);
const loading = ref(true);
const selectedId = ref<number | null>(null);
const duration = ref("1_month");
const dailyLimit = ref(50);
const errorMessage = ref("");
const confirmDisable = ref(false);
const selected = computed(() => accounts.value.find((item) => item.user_id === selectedId.value) ?? null);
const limitDescending = ref(false);
const sortedAccounts = computed(() =>
  [...accounts.value].sort((left, right) => {
    const difference = left.membership.daily_limit - right.membership.daily_limit;
    return limitDescending.value ? -difference : difference;
  }),
);

async function load(): Promise<void> {
  loading.value = true;
  errorMessage.value = "";
  try {
    accounts.value = await api.get<AccountMembership[]>("/admin/memberships");
    if (selectedId.value === null && accounts.value[0]) select(accounts.value[0]);
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "会员列表读取失败。";
  } finally {
    loading.value = false;
  }
}

function select(account: AccountMembership): void {
  selectedId.value = account.user_id;
  dailyLimit.value = account.membership.daily_limit;
  confirmDisable.value = false;
}

async function disable(): Promise<void> {
  if (!confirmDisable.value) {
    confirmDisable.value = true;
    return;
  }
  await update("disable");
  confirmDisable.value = false;
}

async function update(action: "activate" | "disable" | "set_limit"): Promise<void> {
  if (!selected.value) return;
  errorMessage.value = "";
  try {
    await api.patch(`/admin/memberships/${selected.value.user_id}`, {
      action,
      ...(action === "activate" ? { duration: duration.value } : {}),
      daily_limit: dailyLimit.value,
    });
    await load();
    ui.showToast(action === "disable" ? "会员已停用" : "会员设置已保存");
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "会员设置保存失败。";
  }
}

onMounted(load);
</script>

<template>
  <div class="system-grid member-grid">
    <section class="card">
      <header class="card-header"><h2>账号会员状态</h2><span class="tag">{{ accounts.length }} 个账号</span></header>
      <p v-if="loading" class="panel-loading muted">正在读取会员列表</p>
      <p v-else-if="errorMessage" class="panel-loading field-error" role="alert">{{ errorMessage }}</p>
      <div v-else class="table-wrap">
        <table class="data-table">
          <thead><tr><th>账号</th><th>身份</th><th>会员状态</th><th>到期时间</th><th class="num" :aria-sort="limitDescending ? 'descending' : 'ascending'"><button class="sort-button" type="button" @click="limitDescending = !limitDescending">每日上限（次） <span aria-hidden="true">{{ limitDescending ? "↓" : "↑" }}</span></button></th></tr></thead>
          <tbody>
            <tr v-for="account in sortedAccounts" :key="account.user_id" :class="{ selected: selectedId === account.user_id }" @click="select(account)">
              <td class="name-cell">{{ account.username }}</td><td>{{ account.is_admin ? "管理员" : "用户" }}</td><td>{{ account.membership.active ? "有效" : account.membership.status === "disabled" ? "停用" : "未开通" }}</td><td class="numeric">{{ account.membership.is_permanent ? "永久" : account.membership.expires_at?.slice(0, 10) || "" }}</td><td class="num numeric">{{ account.membership.daily_limit }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </section>
    <section class="card member-editor">
      <header class="card-header"><h2>会员设置</h2></header>
      <div v-if="selected" class="card-body form-grid">
        <div class="selected-account"><strong>{{ selected.username }}</strong><span class="tag">{{ selected.membership.active ? "有效" : "未开通" }}</span></div>
        <div class="field"><label for="membership-duration">开通或续期时长</label><select id="membership-duration" v-model="duration" class="select"><option value="1_month">1个月</option><option value="3_months">3个月</option><option value="12_months">12个月</option><option value="3_years">3年</option><option value="permanent">永久</option></select></div>
        <div class="field"><label for="daily-limit">每日智能分析上限</label><input id="daily-limit" v-model.number="dailyLimit" class="input numeric" type="number" min="1" max="1000" /></div>
        <p v-if="errorMessage" class="field-error" role="alert">{{ errorMessage }}</p>
        <button class="btn btn-primary" type="button" @click="update('activate')">开通 / 续期</button>
        <button class="btn" type="button" @click="update('set_limit')">保存每日上限</button>
        <button class="btn" type="button" :disabled="!selected.membership.active" @click="disable">{{ confirmDisable ? "确认停用" : "停用会员" }}</button>
      </div>
      <p v-else class="panel-loading muted">请选择账号</p>
    </section>
  </div>
</template>
