<script setup lang="ts">
import { computed, ref } from "vue";
import { SearchOutlined, ReloadOutlined, ApiOutlined, ArrowRightOutlined, DeleteOutlined, LinkOutlined, SyncOutlined } from "@ant-design/icons-vue";

import StatusBadge from "../components/StatusBadge.vue";
import SurfaceCard from "../components/SurfaceCard.vue";
import { useDesktopRuntime } from "../composables/useDesktopRuntime";
import { showClientActionError } from "../lib/client-errors";
import { formatDateTime, formatRelativeTime, formatVerifiedAtLabel, titleCaseToken } from "../lib/formatters";
import { desktopPublishMediaCatalog } from "../lib/media-catalog";
import type { RuntimeAccount } from "../types";

const { snapshot, refresh, refreshAccounts, loading } = useDesktopRuntime();

const selectedPlatform = ref("all");
const selectedStatus = ref("all");
const searchQuery = ref("");
const bindPendingPlatformId = ref<string | null>(null);
const consolePendingAccountId = ref<string | null>(null);
const unbindPendingAccountId = ref<string | null>(null);
const actionSuccess = ref<string | null>(null);

type AccountAuthState = "authorized" | "expired" | "attention" | "risk";
type AccountRow = Readonly<Omit<RuntimeAccount, "tags">> & { tags: readonly string[] };
const publishPlatformIds = new Set(desktopPublishMediaCatalog.map((item) => item.id));

const accounts = computed(() =>
  (snapshot.value?.accounts ?? []).filter((account) => publishPlatformIds.has(account.platform)),
);

const overview = computed(() => ({
  authorized: accounts.value.filter((item) => item.health === "live").length,
  attention: accounts.value.filter((item) => item.health === "captcha").length,
  risk: accounts.value.filter((item) => item.health === "risk").length,
  onlineClients: snapshot.value?.summary.onlineClients ?? 0,
}));

const platformCards = computed(() =>
  desktopPublishMediaCatalog.map((platform) => {
    const matched = accounts.value.filter((account) => account.platform === platform.id);
    return {
      ...platform,
      count: matched.length,
      latestAccount: matched[0] ?? null,
    };
  }),
);

const statusOptions = [
  { value: "all", label: "全部状态" },
  { value: "authorized", label: "已授权" },
  { value: "attention", label: "待处理" },
  { value: "risk", label: "风险观察" },
  { value: "expired", label: "授权过期" },
] as const;

function platformMeta(platform: string) {
  return (
    desktopPublishMediaCatalog.find((item) => item.id === platform) ?? {
      id: platform,
      label: titleCaseToken(platform),
      shortName: titleCaseToken(platform).slice(0, 1),
      accent: "#64748b",
      loginUrl: null,
      logoUrl: null,
      category: "publish",
      description: "待接入平台",
    }
  );
}

function authState(account: AccountRow): AccountAuthState {
  switch (account.authState) {
    case "active":
      return "authorized";
    case "expired":
    case "revoked":
      return "expired";
    case "challenge_required":
      return "attention";
    default:
      return "risk";
  }
}

function authStateLabel(account: AccountRow): string {
  switch (authState(account)) {
    case "authorized":
      return "已授权";
    case "expired":
      return "授权过期";
    case "attention":
      return "需人工验证";
    default:
      return account.probeState === "network_error" ? "最近校验失败" : "待重新校验";
  }
}

function authStateTone(account: AccountRow) {
  switch (authState(account)) {
    case "authorized":
      return "success" as const;
    case "expired":
      return "danger" as const;
    case "attention":
      return "warn" as const;
    default:
      return "info" as const;
  }
}

function accountInitial(account: AccountRow): string {
  return account.displayName.slice(0, 1).toUpperCase();
}

function sessionStateLabel(account: AccountRow): string {
  switch (account.sessionState) {
    case "hot":
      return "活跃会话";
    case "warm":
      return "本地缓存";
    default:
      return "冷缓存";
  }
}

function verificationTimeLabel(account: AccountRow): string {
  if (account.lastVerifiedAt) {
    return formatVerifiedAtLabel(account.lastVerifiedAt);
  }
  if (account.probeState === "probing") {
    return "正在校验";
  }
  return "尚未校验";
}

const filteredAccounts = computed(() => {
  const keyword = searchQuery.value.trim().toLowerCase();

  return accounts.value.filter((account) => {
    if (selectedPlatform.value !== "all" && account.platform !== selectedPlatform.value) {
      return false;
    }

    if (selectedStatus.value !== "all" && authState(account) !== selectedStatus.value) {
      return false;
    }

    if (!keyword) {
      return true;
    }

    const haystack = [
      account.displayName,
      account.platformUid,
      platformMeta(account.platform).label,
      account.partition,
    ]
      .join(" ")
      .toLowerCase();

    return haystack.includes(keyword);
  });
});

function selectPlatform(platform: string) {
  selectedPlatform.value = platform;
  void refreshAccounts();
}

function resetFilters() {
  selectedPlatform.value = "all";
  selectedStatus.value = "all";
  searchQuery.value = "";
}

async function bindPlatform(platformId: string) {
  bindPendingPlatformId.value = platformId;
  actionSuccess.value = null;

  try {
    const account = await window.desktopBridge.app.bindPublishAccount(platformId);
    selectedPlatform.value = platformId;
    actionSuccess.value = `${account.display_name} 已绑定到 ${platformMeta(platformId).label}`;
    await refresh();
  } catch (error) {
    showClientActionError("bind-account", error);
  } finally {
    bindPendingPlatformId.value = null;
  }
}

async function openConsole(account: AccountRow) {
  consolePendingAccountId.value = account.id;
  try {
    await window.desktopBridge.app.openPublishAccountConsole({
      id: account.id,
      platform: account.platform,
      platformUid: account.platformUid,
      displayName: account.displayName,
    });
  } catch (error) {
    showClientActionError("open-console", error);
  } finally {
    consolePendingAccountId.value = null;
  }
}

async function unbindAccount(account: AccountRow) {
  unbindPendingAccountId.value = account.id;
  actionSuccess.value = null;

  try {
    await window.desktopBridge.app.unbindPublishAccount(account.id, account.syncVersion);
    actionSuccess.value = `${account.displayName} 已解绑`;
    await refresh();
  } catch (error) {
    showClientActionError("unbind-account", error);
  } finally {
    unbindPendingAccountId.value = null;
  }
}

const tableColumns = [
  { title: "昵称 / UID", key: "name", dataIndex: "name" },
  { title: "平台", key: "platform", dataIndex: "platform", width: 140 },
  { title: "授权状态", key: "status", dataIndex: "status", width: 120 },
  { title: "本地会话", key: "session", dataIndex: "session", width: 140 },
  { title: "授权时间", key: "syncTime", dataIndex: "syncTime", width: 180 },
  { title: "操作", key: "actions", align: "right" as const }
];
</script>

<template>
  <section class="page-container">
    <section class="hero-card">
      <div class="hero-header">
        <div class="hero-title">
          <p class="eyebrow">MEDIA ACCOUNT MANAGEMENT</p>
          <h2>媒体账号管理</h2>
        </div>
        <div class="hero-actions">
          <a-button type="primary" ghost class="modern-btn" :loading="loading" @click="refreshAccounts">
            <template #icon><ReloadOutlined /></template>
            刷新状态
          </a-button>
        </div>
      </div>
      <div class="stats-strip">
        <div class="stat-card">
          <div class="stat-label">已授权</div>
          <div class="stat-value">{{ overview.authorized }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">待处理</div>
          <div class="stat-value">{{ overview.attention }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">风险观察</div>
          <div class="stat-value">{{ overview.risk }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">在线客户端</div>
          <div class="stat-value">{{ overview.onlineClients }}</div>
        </div>
      </div>
    </section>

    <!-- Content Sections -->
    <section class="content-section">
      <div class="section-header">
        <h3 class="section-title">选择平台进行授权</h3>
      </div>
      
      <div class="grid-layout">
        <article
          v-for="platform in platformCards"
          :key="platform.id"
          class="modern-card media-card-clickable"
          :class="[
            selectedPlatform === platform.id ? 'is-active' : '',
            platform.latestAccount ? 'is-bound' : 'is-unbound'
          ]"
          @click="selectPlatform(platform.id)"
        >
          <div class="card-header">
            <div class="brand-info">
              <span class="brand-logo" :style="{ color: platform.accent, background: '#ffffff', boxShadow: '0 2px 4px rgba(0,0,0,0.03), inset 0 0 0 1px #e2e8f0' }">
                <img v-if="platform.logoUrl" :src="platform.logoUrl" :alt="platform.label" style="width: 24px; height: 24px; object-fit: contain;" />
                <span v-else>{{ platform.shortName }}</span>
              </span>
              <div class="brand-text">
                <h4>{{ platform.label }}</h4>
                <p>{{ platform.count > 0 ? `${platform.count} 个账号` : "未绑定" }}</p>
              </div>
            </div>
            <!-- Dynamic Status Badge/Tag could be added here if needed -->
          </div>

          <div class="card-footer" style="padding-top: 16px; margin-top: auto; border-top: 1px dashed #e2e8f0; display:flex; justify-content: space-between; align-items:center;">
             <div class="media-card__status" style="display:flex; align-items:center; gap: 8px;">
                <span :class="['status-dot', platform.latestAccount ? 'success' : 'default']"></span>
                <span style="font-size: 13px; color: #64748b; font-weight: 500;">
                   {{ platform.latestAccount ? '已接入' : '待接入' }}
                </span>
             </div>
             
             <div class="action-group">
                <a-button
                  v-if="platform.count > 0"
                  class="action-btn-publish"
                  :loading="bindPendingPlatformId === platform.id"
                  @click.stop="bindPlatform(platform.id)"
                >
                  新增账号
                  <template #icon><ApiOutlined /></template>
                </a-button>
                <a-button
                  v-else
                  type="primary"
                  class="action-btn-bind modern-btn"
                  style="border-radius: 8px; font-weight: 600;"
                  :loading="bindPendingPlatformId === platform.id"
                  @click.stop="bindPlatform(platform.id)"
                >
                  绑定账号
                  <template #icon><ArrowRightOutlined /></template>
                </a-button>
             </div>
          </div>
        </article>
      </div>
    </section>

    <!-- Table Details Section -->
    <section class="content-section">
      <div class="hero-card" style="padding-bottom: 0;">
        <div class="hero-header" style="padding: 24px 32px 16px; border-bottom: 1px solid #eef2f6; align-items: center;">
          <div style="flex: 1;">
            <h3 class="section-title">授权账号列表</h3>
          </div>
          
          <!-- Filters ToolBar -->
          <div style="display: flex; gap: 12px; align-items: center;">
            <a-select v-model:value="selectedPlatform" style="width: 140px; border-radius: 8px;">
              <a-select-option value="all">所有平台</a-select-option>
              <a-select-option v-for="platform in platformCards" :key="platform.id" :value="platform.id">
                {{ platform.label }}
              </a-select-option>
            </a-select>
            <a-select v-model:value="selectedStatus" style="width: 140px;">
              <a-select-option v-for="option in statusOptions" :key="option.value" :value="option.value">
                {{ option.label }}
              </a-select-option>
            </a-select>
            <a-input v-model:value="searchQuery" placeholder="搜索昵称、UID..." style="width: 220px;" allow-clear>
              <template #prefix><SearchOutlined style="color: #94a3b8;" /></template>
            </a-input>
          </div>
        </div>

        <a-table class="modern-table" :columns="tableColumns" :data-source="filteredAccounts" :pagination="false">
          <template #emptyText>
            <div style="padding: 60px; color: #94a3b8;"><a-empty description="暂无匹配账号，请重置过滤或绑定新账号" /></div>
          </template>
          
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'name'">
             <div class="cell-primary-secondary">
               <div class="user-avatar-wrap">
                 <span class="avatar-circle" :style="{ background: platformMeta(record.platform).accent }">
                   <img v-if="record.avatarUrl" :src="record.avatarUrl" :alt="record.displayName" />
                   <span v-else class="avatar-initial">{{ accountInitial(record) }}</span>
                 </span>
                 <div class="info-stack">
                   <span class="title">{{ record.displayName }}</span>
                   <span class="subtitle mono-text">{{ record.platformUid }}</span>
                 </div>
               </div>
             </div>
            </template>
            
            <template v-else-if="column.key === 'platform'">
               <div class="platform-display">
                 <span class="platform-logo-mini">
                   <img v-if="platformMeta(record.platform).logoUrl" :src="platformMeta(record.platform).logoUrl!" />
                   <span v-else :style="{ color: platformMeta(record.platform).accent, fontWeight: 700 }">
                     {{ platformMeta(record.platform).shortName }}
                   </span>
                 </span>
                 <span style="font-weight: 600; font-size: 13px; color: #0f172a;">{{ platformMeta(record.platform).label }}</span>
               </div>
            </template>
            
            <template v-else-if="column.key === 'status'">
               <a-tag :color="authState(record) === 'authorized' ? 'success' : authState(record) === 'expired' ? 'error' : authState(record) === 'attention' ? 'warning' : 'default'" style="border-radius: 999px; font-weight: 600; padding: 2px 10px;">
                 {{ authStateLabel(record) }}
               </a-tag>
            </template>
            
            <template v-else-if="column.key === 'session'">
               <div class="cell-primary-secondary">
                 <div class="info-stack">
                   <span class="title">{{ sessionStateLabel(record) }}</span>
                   <span class="subtitle">{{ record.online ? "本机在线" : "本机离线" }}</span>
                 </div>
               </div>
            </template>
            
            <template v-else-if="column.key === 'syncTime'">
               <div class="cell-primary-secondary">
                 <div class="info-stack">
                   <span class="title">{{ record.lastVerifiedAt ? formatDateTime(record.lastVerifiedAt) : formatDateTime(record.lastSyncAt) }}</span>
                   <span class="subtitle">{{ verificationTimeLabel(record) }} · {{ record.partition }}</span>
                 </div>
               </div>
            </template>
            
            <template v-else-if="column.key === 'actions'">
               <div class="table-actions">
                  <a-tooltip title="打开创作台" placement="top">
                    <a-button type="text" class="action-btn" :loading="consolePendingAccountId === record.id" @click="openConsole(record)">
                      <template #icon><LinkOutlined /></template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip title="重新授权" placement="top">
                    <a-button type="text" class="action-btn" :loading="bindPendingPlatformId === record.platform" @click="bindPlatform(record.platform)">
                      <template #icon><SyncOutlined /></template>
                    </a-button>
                  </a-tooltip>
                  <a-popconfirm title="确定解绑这个账号？" placement="topRight" @confirm="unbindAccount(record)">
                     <a-tooltip title="解绑" placement="top">
                        <a-button danger type="text" class="action-btn danger-btn" :loading="unbindPendingAccountId === record.id">
                          <template #icon><DeleteOutlined /></template>
                        </a-button>
                     </a-tooltip>
                  </a-popconfirm>
               </div>
            </template>
          </template>
        </a-table>
      </div>
    </section>
  </section>
</template>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  gap: 32px;
  padding-bottom: 40px;
  max-width: 1400px;
}

/* Hero Section */
.hero-card {
  background: #ffffff;
  border-radius: 20px;
  border: 1px solid #eef2f6;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px -2px rgba(0, 0, 0, 0.01);
  overflow: hidden;
}

.hero-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 36px 40px;
}

.eyebrow {
  margin: 0 0 12px;
  color: #64748b;
  font-size: 13px;
  font-weight: 700;
  letter-spacing: 0.1em;
  text-transform: uppercase;
}

.hero-title h2 {
  margin: 0;
  font-size: 32px;
  font-weight: 800;
  color: #0f172a;
  letter-spacing: -0.02em;
}

.summary {
  margin: 16px 0 0;
  max-width: 800px;
  color: #475569;
  line-height: 1.6;
  font-size: 15px;
}

.modern-btn {
  border-radius: 8px;
  height: 40px;
  padding: 0 20px;
  font-weight: 600;
}

/* Stats Strip */
.stats-strip {
  display: flex;
  padding: 24px 40px;
  background: #f8fafc;
  border-top: 1px solid #eef2f6;
  gap: 40px;
}

.stat-card {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.stat-label {
  font-size: 14px;
  font-weight: 500;
  color: #64748b;
}

.stat-value {
  font-size: 40px;
  font-weight: 700;
  color: #0f172a;
  line-height: 1;
  font-feature-settings: "tnum";
}

/* Content Section */
.content-section {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.section-header {
  padding: 0 8px;
}

.section-title {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: #0f172a;
}

.section-desc {
  margin: 8px 0 0;
  color: #64748b;
  font-size: 15px;
  line-height: 1.5;
}

.grid-layout {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

/* Modern Card Layout */
.modern-card {
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 20px;
  border: 1px solid #e2e8f0;
  padding: 24px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.02);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.media-card-clickable {
  cursor: pointer;
}

.media-card-clickable:hover {
  transform: translateY(-4px);
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.01);
  border-color: #cbd5e1;
}

.modern-card.is-active {
  border-color: #0ea5e9;
  box-shadow: 0 0 0 1px #0ea5e9, 0 4px 6px -1px rgba(14, 165, 233, 0.1);
  background: #f0f9ff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px; /* Reduced because content goes into footer */
}

.brand-info {
  display: flex;
  gap: 16px;
  align-items: center;
}

.brand-logo {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  font-size: 20px;
  font-weight: 800;
}

.brand-text h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 700;
  color: #0f172a;
}

.brand-text p {
  margin: 4px 0 0;
  color: #64748b;
  font-size: 13px;
  font-weight: 500;
}

.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
.status-dot.success { background-color: #10b981; }
.status-dot.default { background-color: #cbd5e1; }

.action-btn-publish {
  border-radius: 8px;
  font-size: 13px;
  font-weight: 600;
  color: #0284c7;
  background: #e0f2fe;
  border: 1px solid #bae6fd;
  height: 34px;
  padding: 0 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s ease;
}
.action-btn-publish:hover {
  background: #bae6fd;
  color: #0369a1;
  border-color: #7dd3fc;
}

.action-btn-bind {
  border-radius: 8px;
  height: 34px;
}

/* Modern Enterprise Table Styles */
:deep(.modern-table) {
  padding: 0 32px 32px;
}

:deep(.modern-table .ant-table-thead > tr > th) {
  background-color: transparent !important;
  color: #64748b;
  font-weight: 600;
  font-size: 13px;
  border-bottom: 1px solid #e2e8f0;
  padding: 16px 12px;
}

:deep(.modern-table .ant-table-tbody > tr > td) {
  padding: 16px 12px;
  border-bottom: 1px solid #f1f5f9;
  color: #0f172a;
}

:deep(.modern-table .ant-table-tbody > tr:last-child > td) {
  border-bottom: none;
}

:deep(.modern-table .ant-table-tbody > tr:hover > td) {
  background-color: #f8fafc !important;
}

.cell-primary-secondary {
  display: flex;
  flex-direction: column;
}
.info-stack {
  display: flex;
  flex-direction: column;
}
.info-stack .title {
  font-weight: 600;
  color: #0f172a;
  font-size: 14px;
}
.info-stack .subtitle {
  color: #64748b;
  font-size: 13px;
  margin-top: 4px;
}
.info-stack .mono-text {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}

.user-avatar-wrap {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-circle {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.05);
}
.avatar-circle img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.avatar-initial {
  color: #ffffff;
  font-size: 16px;
  font-weight: 700;
}

.platform-display {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  color: #0f172a;
}
.platform-logo-mini {
  width: 32px;
  height: 32px;
  background: #ffffff;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05), inset 0 0 0 1px #e2e8f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}
.platform-logo-mini img {
  width: 20px;
  height: 20px;
  object-fit: contain;
}

.table-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  align-items: center;
}

/* Responsiveness */
@media (max-width: 1024px) {
  .hero-header {
    flex-direction: column;
    gap: 24px;
  }
  .stats-strip {
    flex-wrap: wrap;
    gap: 24px;
  }
}
</style>
