import { Text, View } from "@tarojs/components";
import { useDidShow, useRouter } from "@tarojs/taro";
import { useState } from "react";
import { AgentKnowledgeSourceDetail, getAgentKnowledgeSourceDetail } from "../../api/agent";
import "./index.scss";

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

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

function trustScoreText(value?: number) {
  const score = Number(value);
  if (!Number.isFinite(score)) return "";
  return `${Math.round(Math.max(0, Math.min(1, score)) * 100)}%`;
}

export default function KnowledgeSourceDetailPage() {
  const { params } = useRouter();
  const id = params?.id || "";
  const [detail, setDetail] = useState<AgentKnowledgeSourceDetail | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useDidShow(() => {
    if (!id) {
      setError("缺少知识来源ID");
      return;
    }
    void (async () => {
      setLoading(true);
      try {
        const data = await getAgentKnowledgeSourceDetail(id);
        setDetail(data || null);
        setError("");
      } catch (e) {
        setError(e instanceof Error ? e.message : "加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  const content = asText(detail?.contentText || detail?.content, "");
  const tags = Array.isArray(detail?.tagList) ? detail.tagList : [];
  const updatedAt = asText(detail?.updatedAt || detail?.createdAt, "");
  const trustLabel = asText(detail?.trustLabel, "");
  const trustScore = trustScoreText(detail?.trustScore);
  const revisionCount = Number(detail?.revisionCount || 0);
  const trustLevel = String(detail?.trustLevel || "standard");

  return (
    <View className="knowledge-source-page">
      {error ? (
        <View className="knowledge-source-state is-error">
          <Text>{error}</Text>
        </View>
      ) : null}

      {loading ? (
        <View className="knowledge-source-state">
          <Text>加载中...</Text>
        </View>
      ) : null}

      <View className="knowledge-source-header">
        <View className="knowledge-source-header__labels">
          <Text className="knowledge-source-header__label">知识库</Text>
          <Text className="knowledge-source-header__label is-muted">{sourceTypeText(detail?.sourceType)}</Text>
          {trustLabel ? (
            <Text className={`knowledge-source-header__label is-trust is-${trustLevel}`}>
              {trustScore ? `${trustLabel} ${trustScore}` : trustLabel}
            </Text>
          ) : null}
        </View>
        <Text className="knowledge-source-header__title">{asText(detail?.title)}</Text>
        <View className="knowledge-source-header__meta">
          <Text>{updatedAt ? `更新 ${updatedAt}` : "-"}</Text>
          {detail?.lastRevisedAt ? <Text>{`修订 ${detail.lastRevisedAt}`}</Text> : null}
          {revisionCount > 0 ? <Text>{`版本 ${revisionCount}`}</Text> : null}
          {detail?.verifiedAt ? <Text>{`核验 ${detail.verifiedAt}`}</Text> : null}
          {detail?.fileName ? <Text>{detail.fileName}</Text> : null}
        </View>
      </View>

      {tags.length ? (
        <View className="knowledge-source-tags">
          {tags.map((tag) => (
            <Text key={tag} className="knowledge-source-tag">
              {tag}
            </Text>
          ))}
        </View>
      ) : null}

      {detail?.summary ? (
        <View className="knowledge-source-section">
          <Text className="knowledge-source-section__title">摘要</Text>
          <Text className="knowledge-source-section__body">{detail.summary}</Text>
        </View>
      ) : null}

      <View className="knowledge-source-section">
        <Text className="knowledge-source-section__title">正文</Text>
        <Text className="knowledge-source-section__body">{content || "暂无内容"}</Text>
      </View>
    </View>
  );
}
