import { useQuery } from "@tanstack/react-query";
import { useParams, Link } from "react-router-dom";
import { api } from "../lib/api";

const TYPE_LABELS: Record<string, string> = {
  overview: "總覽",
  principleMap: "心法地圖",
  quiz: "練習題庫",
  category: "學習分類",
  case: "案例講解",
  term: "名詞",
  company: "公司",
  episode: "單集",
  principle: "心法原則",
};

export default function LibraryDetail() {
  const { kind, id } = useParams<{ kind: string; id: string }>();
  const kbQ = useQuery({ queryKey: ["knowledge"], queryFn: api.knowledge, staleTime: 60_000 });
  const noteQ = useQuery({
    queryKey: ["note", kind, id],
    queryFn: () => api.knowledgeNote(kind || "", id || ""),
    enabled: !!kind && !!id && kind !== "principle",
  });

  if (kbQ.isLoading) return <div className="page"><div className="loading">載入中...</div></div>;

  const data = kbQ.data;

  let title = id || "";
  let body = "";
  let extraMeta: Record<string, any> | null = null;

  if (kind === "principle") {
    const p = data?.principles?.find(p => p.id === id || encodeURIComponent(p.id) === id);
    if (p) {
      title = p.title;
      body = p.body;
      extraMeta = { num: p.num, summary: p.summary };
    }
  } else if (kind === "overview" && data?.overview) {
    title = data.overview.title;
    body = data.overview.body;
  } else if (kind === "principleMap" && data?.principleMap) {
    title = data.principleMap.title;
    body = data.principleMap.body;
  } else if (kind === "quiz" && data?.quiz) {
    title = data.quiz.title;
    body = data.quiz.body;
  } else if (kind === "category") {
    const c = data?.categories?.find(c => c.id === id || encodeURIComponent(c.id) === id);
    if (c) { title = c.title; body = c.body; extraMeta = c.frontmatter || null; }
  } else if (kind === "case") {
    const c = data?.cases?.find(c => c.id === id || encodeURIComponent(c.id) === id);
    if (c) { title = c.title; body = c.body; extraMeta = c.frontmatter || null; }
  } else if (kind === "term" || kind === "company" || kind === "episode") {
    if (noteQ.data) {
      title = noteQ.data.title;
      body = noteQ.data.body;
      extraMeta = noteQ.data.frontmatter || null;
    } else if (data?.index) {
      const item = data.index.find(i => i.id === id && i.kind?.startsWith(kind || ""));
      if (item) title = item.title;
      if (!body) body = `# ${title}\n\n（尚未擷取全文，請執行 npm run build:knowledge 更新）`;
    }
  }

  return (
    <div className="page library-detail-page">
      <div className="page-head">
        <Link to="/library" className="btn btn-sm">← 回圖書館</Link>
        <h1>{title}</h1>
        <p className="page-subtitle">{TYPE_LABELS[kind || ""] || kind}</p>
        {extraMeta && (
          <div className="ld-meta">
            {Object.entries(extraMeta).map(([k, v]) =>
              v != null && <span key={k} className="tag">{k}: {String(v).slice(0, 60)}</span>
            )}
          </div>
        )}
      </div>

      <div className="ld-body markdown-body">
        {body ? (
          <RenderMarkdown text={body} />
        ) : (
          <div className="text-dim">暫無內容</div>
        )}
      </div>
    </div>
  );
}

function RenderMarkdown({ text }: { text: string }) {
  const lines = text.split("\n");
  const html = lines
    .map(line => {
      if (line.startsWith("### ")) return `<h3>${escapeHtml(line.slice(4))}</h3>`;
      if (line.startsWith("## ")) return `<h2>${escapeHtml(line.slice(3))}</h2>`;
      if (line.startsWith("# ")) return `<h1>${escapeHtml(line.slice(2))}</h1>`;
      if (line.startsWith("> ")) return `<blockquote>${escapeHtml(line.slice(2))}</blockquote>`;
      if (line.startsWith("- ") || line.startsWith("* ")) return `<li>${escapeHtml(line.slice(2))}</li>`;
      if (line.trim() === "") return "<br/>";
      if (line.match(/^\d+\.\s/)) return `<li>${escapeHtml(line.replace(/^\d+\.\s/, ""))}</li>`;
      return `<p>${escapeHtml(line)}</p>`;
    })
    .join("\n");

  return <div dangerouslySetInnerHTML={{ __html: html }} />;
}

function escapeHtml(s: string) {
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
