import { Button, ScrollView, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import AdminGuard from "../../components/AdminGuard";
import { useUserStore } from "../../store/user";
import {
  AgentOpsAlertCheckResult,
  AgentOpsOverview,
  AgentReadiness,
  checkAgentOpsAlerts,
  getAgentOpsOverview,
  getAgentReadiness,
} from "../../api/agent";
import "./index.scss";

type AdminAction = {
  title: string;
  desc: string;
  target: string;
  tone: "blue" | "green" | "orange" | "slate";
};

const ACTIONS: AdminAction[] = [
  { title: "AI运维", desc: "模型健康、发布门槛、告警检查", target: "/pages/admin-agent-debug/index", tone: "blue" },
  { title: "知识治理", desc: "知识源可信度、状态、重建索引", target: "/pages/admin-knowledge-governance/index", tone: "green" },
  { title: "待审批", desc: "内容、活动、问卷、服务事项审核", target: "/pages/admin-pending/index", tone: "orange" },
  { title: "数据中枢", desc: "后台数据指挥能力在Web管理端使用", target: "", tone: "slate" },
];

function asMap(value: unknown): Record<string, unknown> {
  return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
}

function text(value: unknown, fallback = "-") {
  if (value === null || value === undefined) return fallback;
  const next = String(value).trim();
  return next || fallback;
}

function statusText(value: unknown) {
  const status = text(value, "unknown");
  const map: Record<string, string> = {
    healthy: "健康",
    ready: "就绪",
    passed: "通过",
    watch: "观察",
    critical: "严重",
    blocked: "阻断",
    failed: "异常",
  };
  return map[status] || status;
}

export default function AdminLivePage() {
  const adminUser = useUserStore((s) => s.adminUser);
  const [ops, setOps] = useState<AgentOpsOverview | null>(null);
  const [readiness, setReadiness] = useState<AgentReadiness | null>(null);
  const [alertResult, setAlertResult] = useState<AgentOpsAlertCheckResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [running, setRunning] = useState(false);

  const health = asMap(ops?.health);
  const chat = asMap(ops?.chat);
  const knowledge = asMap(ops?.knowledge);
  const action = asMap(ops?.action);
  const readinessTotals = asMap(readiness?.totals);

  const metrics = useMemo(() => [
    { label: "运行状态", value: statusText(health.status), note: text(health.summary, "暂无摘要") },
    { label: "会话", value: text(chat.conversationCount ?? chat.conversations, "0"), note: "Agent会话" },
    { label: "知识", value: text(knowledge.sourceCount ?? knowledge.activeSourceCount, "0"), note: "可用知识源" },
    { label: "动作", value: text(action.openCount ?? action.requestCount, "0"), note: "待处理动作" },
  ], [action, chat, health, knowledge]);

  async function refresh() {
    setLoading(true);
    try {
      const [opsData, readinessData] = await Promise.all([
        getAgentOpsOverview(),
        getAgentReadiness().catch(() => null),
      ]);
      setOps(opsData);
      setReadiness(readinessData);
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "加载失败", icon: "none" });
    } finally {
      setLoading(false);
    }
  }

  async function runAlertCheck() {
    setRunning(true);
    try {
      const result = await checkAgentOpsAlerts({
        notifyAdmins: true,
        resolveHealthy: true,
        minimumNotifySeverity: "critical",
      });
      setAlertResult(result);
      await refresh();
      Taro.showToast({ title: "检查完成", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "检查失败", icon: "none" });
    } finally {
      setRunning(false);
    }
  }

  function openAction(item: AdminAction) {
    if (item.target) {
      Taro.navigateTo({ url: item.target });
      return;
    }
    Taro.showToast({ title: "请在Web后台使用数据中枢", icon: "none" });
  }

  useDidShow(() => {
    void refresh();
  });

  return (
    <AdminGuard>
      <View className="page-shell admin-live">
        <ScrollView scrollY className="admin-live__scroll">
          <View className="admin-live__hero">
            <Text className="admin-live__eyebrow">管理员模式</Text>
            <Text className="admin-live__title">连小新后台</Text>
            <Text className="admin-live__subtitle">
              {text(adminUser?.name, "管理员")} · 只展示后台权限能力
            </Text>
          </View>

          <View className="admin-live__body">
            <View className="admin-live__assistant-card">
              <View className="admin-live__avatar">
                <Text>AI</Text>
              </View>
              <View className="admin-live__assistant-copy">
                <Text className="admin-live__assistant-title">后台智能工作台</Text>
                <Text className="admin-live__assistant-text">
                  这里不会复用会员端会话，也不会展示用户端授权卡片。管理员功能走后台账号和 ai:operate 权限。
                </Text>
              </View>
            </View>

            <View className="admin-live__metrics">
              {metrics.map((item) => (
                <View key={item.label} className="admin-live__metric">
                  <Text className="admin-live__metric-label">{item.label}</Text>
                  <Text className="admin-live__metric-value">{item.value}</Text>
                  <Text className="admin-live__metric-note">{item.note}</Text>
                </View>
              ))}
            </View>

            <View className="admin-live__actions">
              {ACTIONS.map((item) => (
                <View
                  key={item.title}
                  className={`admin-live__action-card admin-live__action-card--${item.tone}`}
                  onClick={() => openAction(item)}
                >
                  <Text className="admin-live__action-title">{item.title}</Text>
                  <Text className="admin-live__action-desc">{item.desc}</Text>
                  <Text className="admin-live__action-arrow">&gt;</Text>
                </View>
              ))}
            </View>

            <View className="admin-live__ops-panel">
              <View>
                <Text className="admin-live__ops-title">运维动作</Text>
                <Text className="admin-live__ops-sub">
                  {alertResult ? `本次扫描 ${text(alertResult.activeAlertCount, "0")} 个开放告警` : `就绪项 ${text(readinessTotals.ready ?? readinessTotals.passed, "0")}`}
                </Text>
              </View>
              <View className="admin-live__ops-buttons">
                <Button className="admin-live__button ghost" loading={loading} disabled={loading || running} onClick={refresh}>
                  刷新
                </Button>
                <Button className="admin-live__button primary" loading={running} disabled={loading || running} onClick={runAlertCheck}>
                  告警检查
                </Button>
              </View>
            </View>
          </View>
        </ScrollView>
      </View>
    </AdminGuard>
  );
}
