import { Button, Input, Picker, Text, Textarea, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import AdminGuard from "../../components/AdminGuard";
import {
  ConsoleKnowledgeRevision,
  ConsoleKnowledgeSource,
  listConsoleKnowledgeRevisions,
  listConsoleKnowledgeSources,
  reindexConsoleKnowledge,
  updateConsoleKnowledgeStatus,
  updateConsoleKnowledgeTrust,
} from "../../api/agent";
import "./index.scss";

const QUALITY_OPTIONS = [
  { label: "全部", value: "all" },
  { label: "已过期", value: "expired" },
  { label: "即将过期", value: "expiring" },
  { label: "低可信", value: "low_trust" },
  { label: "未核验", value: "unverified" },
];

const STATUS_OPTIONS = [
  { label: "全部", value: "" },
  { label: "已发布", value: "active" },
  { label: "草稿", value: "draft" },
];

const TRUST_LEVELS = [
  { label: "待核验", value: "low" },
  { label: "标准可信", value: "standard" },
  { label: "已核验", value: "verified" },
  { label: "官方认证", value: "official" },
];

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

function asNumber(value: unknown, fallback = 0) {
  const num = Number(value);
  return Number.isFinite(num) ? num : fallback;
}

function trustPercent(item?: ConsoleKnowledgeSource) {
  return `${Math.round(Math.max(0, Math.min(1, asNumber(item?.trustScore ?? item?.trust_score, 0))) * 100)}%`;
}

function trustLabel(value?: string) {
  return TRUST_LEVELS.find((item) => item.value === value)?.label || value || "标准可信";
}

function sourceTypeText(value?: string) {
  const map: Record<string, string> = {
    text: "文本",
    pdf: "PDF",
    docx: "文档",
    doc: "文档",
    policy: "政策",
    faq: "问答",
    guide: "指南",
    regulation: "制度",
  };
  return map[value || ""] || value || "知识";
}

export default function AdminKnowledgeGovernancePage() {
  const [quality, setQuality] = useState("all");
  const [status, setStatus] = useState("");
  const [sources, setSources] = useState<ConsoleKnowledgeSource[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [selected, setSelected] = useState<ConsoleKnowledgeSource | null>(null);
  const [revisions, setRevisions] = useState<ConsoleKnowledgeRevision[]>([]);
  const [trustScore, setTrustScore] = useState("0.7");
  const [trustLevel, setTrustLevel] = useState("standard");
  const [note, setNote] = useState("");

  const selectedId = Number(selected?.id || 0);
  const qualityLabel = useMemo(() => QUALITY_OPTIONS.find((item) => item.value === quality)?.label || "全部", [quality]);
  const statusLabel = useMemo(() => STATUS_OPTIONS.find((item) => item.value === status)?.label || "全部", [status]);

  async function refresh(nextQuality = quality, nextStatus = status) {
    setLoading(true);
    try {
      const data = await listConsoleKnowledgeSources({
        quality: nextQuality,
        status: nextStatus || undefined,
        page: 1,
        size: 50,
      });
      setSources(data.records || []);
      setTotal(Number(data.total || 0));
      if (selectedId && !(data.records || []).some((item) => Number(item.id) === selectedId)) {
        setSelected(null);
        setRevisions([]);
      }
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "加载失败", icon: "none" });
    } finally {
      setLoading(false);
    }
  }

  async function selectSource(item: ConsoleKnowledgeSource) {
    setSelected(item);
    setTrustScore(String(item.trustScore ?? item.trust_score ?? 0.7));
    setTrustLevel(String(item.trustLevel ?? item.trust_level ?? "standard"));
    setNote("");
    try {
      setRevisions(await listConsoleKnowledgeRevisions(Number(item.id), 20));
    } catch {
      setRevisions([]);
    }
  }

  async function saveTrust() {
    if (!selectedId) return;
    const score = Math.max(0, Math.min(1, Number(trustScore)));
    if (!Number.isFinite(score)) {
      Taro.showToast({ title: "可信分需为0到1", icon: "none" });
      return;
    }
    setLoading(true);
    try {
      await updateConsoleKnowledgeTrust(selectedId, { trustScore: score, trustLevel, note });
      Taro.showToast({ title: "已更新可信度", icon: "success" });
      await refresh();
      const latest = sources.find((item) => Number(item.id) === selectedId) || selected;
      if (latest) await selectSource({ ...latest, trustScore: score, trustLevel });
    } finally {
      setLoading(false);
    }
  }

  async function toggleStatus(item: ConsoleKnowledgeSource) {
    const nextStatus = item.status === "active" ? "draft" : "active";
    setLoading(true);
    try {
      await updateConsoleKnowledgeStatus(Number(item.id), nextStatus);
      Taro.showToast({ title: nextStatus === "active" ? "已发布" : "已退回草稿", icon: "success" });
      await refresh();
    } finally {
      setLoading(false);
    }
  }

  async function runReindex() {
    setLoading(true);
    try {
      await reindexConsoleKnowledge();
      Taro.showToast({ title: "已重建索引", icon: "success" });
    } finally {
      setLoading(false);
    }
  }

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

  return (
    <AdminGuard>
      <View className="knowledge-admin">
        <View className="knowledge-admin__header">
          <View>
            <Text className="knowledge-admin__title">知识源治理</Text>
            <Text className="knowledge-admin__subtitle">发布状态、可信度、过期风险和修订历史</Text>
          </View>
          <Button className="knowledge-admin__icon-button" loading={loading} disabled={loading} onClick={runReindex}>
            索引
          </Button>
        </View>

        <View className="knowledge-admin__filters">
          <Picker
            mode="selector"
            range={QUALITY_OPTIONS.map((item) => item.label)}
            value={Math.max(0, QUALITY_OPTIONS.findIndex((item) => item.value === quality))}
            onChange={(e) => {
              const next = QUALITY_OPTIONS[Number(e.detail.value)]?.value || "all";
              setQuality(next);
              void refresh(next, status);
            }}
          >
            <View className="knowledge-admin__filter">
              <Text>质量</Text>
              <Text>{qualityLabel}</Text>
            </View>
          </Picker>
          <Picker
            mode="selector"
            range={STATUS_OPTIONS.map((item) => item.label)}
            value={Math.max(0, STATUS_OPTIONS.findIndex((item) => item.value === status))}
            onChange={(e) => {
              const next = STATUS_OPTIONS[Number(e.detail.value)]?.value || "";
              setStatus(next);
              void refresh(quality, next);
            }}
          >
            <View className="knowledge-admin__filter">
              <Text>状态</Text>
              <Text>{statusLabel}</Text>
            </View>
          </Picker>
          <Button className="knowledge-admin__filter-button" loading={loading} disabled={loading} onClick={() => refresh()}>
            刷新
          </Button>
        </View>

        <View className="knowledge-admin__summary">
          <Text>共 {total} 条</Text>
          <Text>{qualityLabel} · {statusLabel}</Text>
        </View>

        <View className="knowledge-admin__list">
          {sources.map((item) => {
            const itemTrustLevel = String(item.trustLevel ?? item.trust_level ?? "standard");
            const active = Number(item.id) === selectedId;
            return (
              <View
                key={item.id}
                className={`knowledge-admin-card ${active ? "is-active" : ""}`}
                onClick={() => selectSource(item)}
              >
                <View className="knowledge-admin-card__main">
                  <View className="knowledge-admin-card__labels">
                    <Text className={`knowledge-admin-badge is-${item.status || "draft"}`}>
                      {item.status === "active" ? "已发布" : "草稿"}
                    </Text>
                    <Text className={`knowledge-admin-badge is-trust-${itemTrustLevel}`}>
                      {trustLabel(itemTrustLevel)} {trustPercent(item)}
                    </Text>
                    <Text className="knowledge-admin-badge is-muted">{sourceTypeText(item.sourceType || item.source_type)}</Text>
                  </View>
                  <Text className="knowledge-admin-card__title">{asText(item.title)}</Text>
                  <Text className="knowledge-admin-card__meta">
                    版本 {asText(item.revisionCount ?? item.revision_count, "0")} · 过期 {asText(item.expireDate, "无")} · 核验 {asText(item.verifiedAt, "未核验")}
                  </Text>
                </View>
                <Button
                  className="knowledge-admin-card__action"
                  disabled={loading}
                  onClick={(event) => {
                    event.stopPropagation();
                    void toggleStatus(item);
                  }}
                >
                  {item.status === "active" ? "退回" : "发布"}
                </Button>
              </View>
            );
          })}
          {!sources.length ? <Text className="knowledge-admin__empty">暂无知识源</Text> : null}
        </View>

        {selected ? (
          <View className="knowledge-admin-detail">
            <Text className="knowledge-admin-detail__title">{asText(selected.title)}</Text>
            <View className="knowledge-admin-form">
              <View className="knowledge-admin-form__row">
                <Text>可信分</Text>
                <Input
                  className="knowledge-admin-form__input"
                  type="digit"
                  value={trustScore}
                  onInput={(e) => setTrustScore(String(e.detail.value))}
                />
              </View>
              <Picker
                mode="selector"
                range={TRUST_LEVELS.map((item) => item.label)}
                value={Math.max(0, TRUST_LEVELS.findIndex((item) => item.value === trustLevel))}
                onChange={(e) => setTrustLevel(TRUST_LEVELS[Number(e.detail.value)]?.value || "standard")}
              >
                <View className="knowledge-admin-form__row">
                  <Text>可信等级</Text>
                  <Text>{trustLabel(trustLevel)}</Text>
                </View>
              </Picker>
              <Textarea
                className="knowledge-admin-form__textarea"
                value={note}
                maxlength={180}
                placeholder="填写本次治理说明"
                onInput={(e) => setNote(String(e.detail.value))}
              />
              <Button className="knowledge-admin__primary-button" loading={loading} disabled={loading} onClick={saveTrust}>
                保存可信度
              </Button>
            </View>

            <View className="knowledge-admin-revisions">
              <Text className="knowledge-admin-revisions__title">修订历史</Text>
              {revisions.map((item) => (
                <View key={item.id} className="knowledge-admin-revision">
                  <Text className="knowledge-admin-revision__head">
                    #{asText(item.revisionNo)} · {asText(item.eventType)} · {asText(item.createdAt)}
                  </Text>
                  <Text className="knowledge-admin-revision__body">
                    {asText(item.changeNote, "无说明")} · {trustLabel(item.trustLevel)} {Math.round(asNumber(item.trustScore, 0) * 100)}%
                  </Text>
                </View>
              ))}
              {!revisions.length ? <Text className="knowledge-admin__empty">暂无修订记录</Text> : null}
            </View>
          </View>
        ) : null}
      </View>
    </AdminGuard>
  );
}
