import { useState, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { Link, useSearchParams } from "react-router-dom";
import { api } from "../lib/api";
import type { KnowledgePayload, KnowledgeNote, KnowledgePrinciple } from "../lib/api";
import { RouteIcon } from "../components/PixelIcons";

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

const TYPE_ICONS: Record<string, string> = {
  category: "book",
  case: "sword",
  term: "flow",
  company: "castle",
  episode: "world",
  principle: "scroll",
};

function highlightText(text: string, query: string) {
  if (!query.trim()) return text;
  const parts = text.split(new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi'));
  return parts.map((p, i) =>
    p.toLowerCase() === query.toLowerCase() ? <mark key={i} className="hl">{p}</mark> : p
  );
}

function PrincipleCard({ p, query }: { p: KnowledgePrinciple; query: string }) {
  return (
    <Link to={`/library/principle/${encodeURIComponent(p.id)}`} className="lc-card">
      <div className="lc-card-icon">
        <RouteIcon to="/skills" size={20} />
      </div>
      <div className="lc-card-body">
        <div className="lc-card-title">{highlightText(p.title, query)}</div>
        {p.summary && <div className="lc-card-summary">{highlightText(p.summary.slice(0, 120), query)}</div>}
        <div className="lc-card-meta">
          <span className="tag tag-principle">心法</span>
          {p.num && <span className="tag">#{p.num}</span>}
        </div>
      </div>
    </Link>
  );
}

function NoteCard({ note, kind, query }: { note: KnowledgeNote; kind: string; query: string }) {
  const icon = TYPE_ICONS[kind] || "book";
  return (
    <Link to={`/library/${kind}/${encodeURIComponent(note.id)}`} className="lc-card">
      <div className="lc-card-icon">
        <RouteIcon to={kind === "case" ? "/skills" : kind === "company" ? "/research" : "/"} size={20} />
      </div>
      <div className="lc-card-body">
        <div className="lc-card-title">{highlightText(note.title, query)}</div>
        {note.summary && <div className="lc-card-summary">{highlightText(note.summary.slice(0, 120), query)}</div>}
        <div className="lc-card-meta">
          <span className={`tag tag-${kind}`}>{TYPE_LABELS[kind] || kind}</span>
        </div>
      </div>
    </Link>
  );
}

function IndexItemRow({ item, query }: { item: NonNullable<KnowledgePayload["index"]>[number]; query: string }) {
  const kind = item.kind?.split(":")[0] || "term";
  const link = kind === "company" ? `/library/company/${item.id}`
    : kind === "episode" ? `/library/episode/${item.id}`
    : `/library/term/${item.id}`;
  return (
    <Link to={link} className="lc-index-row">
      <span className={`tag tag-${kind}`}>{TYPE_LABELS[kind] || kind}</span>
      <span>{highlightText(item.title, query)}</span>
      {item.aliases && item.aliases.length > 0 && (
        <span className="lc-aliases">{item.aliases.join(", ")}</span>
      )}
    </Link>
  );
}

export default function Library() {
  const [searchParams, setSearchParams] = useSearchParams();
  const query = searchParams.get("q") || "";
  const typeFilter = searchParams.get("type") || "";
  const [showFilters, setShowFilters] = useState(false);

  const kbQ = useQuery({ queryKey: ["knowledge"], queryFn: api.knowledge, staleTime: 60_000 });

  const data = kbQ.data;

  const filtered = useMemo(() => {
    if (!data) return null;
    const q = query.toLowerCase().trim();

    const matchText = (text: string) => !q || text.toLowerCase().includes(q);
    const matchType = (t: string) => !typeFilter || t === typeFilter;

    const out: {
      principles: KnowledgePrinciple[];
      categories: KnowledgeNote[];
      cases: KnowledgeNote[];
      terms: { id: string; title: string; body?: string }[];
      companies: { id: string; title: string; body?: string }[];
      episodes: { id: string; title: string; body?: string }[];
      index: NonNullable<KnowledgePayload["index"]>;
    } = { principles: [], categories: [], cases: [], terms: [], companies: [], episodes: [], index: [] };

    if (matchType("principle") || !typeFilter) {
      out.principles = (data.principles || []).filter(p => matchText(p.title) || matchText(p.summary || "") || matchText(p.body));
    }

    if (matchType("category") || !typeFilter) {
      out.categories = (data.categories || []).filter(c => matchText(c.title) || matchText(c.summary || ""));
    }

    if (matchType("case") || !typeFilter) {
      out.cases = (data.cases || []).filter(c => matchText(c.title) || matchText(c.summary || ""));
    }

    if (data.index) {
      out.index = data.index.filter(item => {
        const kind = item.kind?.split(":")[0] || "term";
        return matchType(kind) && (matchText(item.title) || (item.aliases || []).some(a => a.toLowerCase().includes(q)));
      });
    }

    return out;
  }, [data, query, typeFilter]);

  if (kbQ.isLoading) return <div className="page"><div className="loading">載入知識庫中...</div></div>;
  if (kbQ.error) return <div className="page"><div className="error">載入失敗</div></div>;

  const hasData = data && (data.principles?.length || data.categories?.length || data.cases?.length || data.index?.length);

  return (
    <div className="page library-page">
      <div className="page-head">
        <h1>知識圖書館</h1>
        <p className="page-subtitle">瀏覽所有心法、案例、名詞、公司研究與單集筆記</p>
      </div>

      <div className="lc-toolbar">
        <input
          type="text"
          className="lc-search"
          placeholder="搜尋知識庫..."
          value={query}
          onChange={e => {
            const p = new URLSearchParams(searchParams);
            if (e.target.value) p.set("q", e.target.value); else p.delete("q");
            setSearchParams(p);
          }}
        />
        <button className="btn btn-sm" onClick={() => setShowFilters(!showFilters)}>
          {typeFilter ? `${TYPE_LABELS[typeFilter] || typeFilter} ✕` : "過濾器 ▾"}
        </button>
      </div>

      {showFilters && (
        <div className="lc-filters">
          {["", "principle", "category", "case", "term", "company", "episode"].map(t => (
            <button
              key={t}
              className={`btn btn-sm ${typeFilter === t ? "btn-active" : ""}`}
              onClick={() => {
                const p = new URLSearchParams(searchParams);
                if (t) p.set("type", t); else p.delete("type");
                setSearchParams(p);
              }}
            >
              {TYPE_LABELS[t] || "全部"}
            </button>
          ))}
        </div>
      )}

      {data?.overview && !query && !typeFilter && (
        <section className="lc-section">
          <h2 className="lc-section-title">
            <RouteIcon to="/" size={18} /> 總覽
          </h2>
          <div className="lc-overview-preview">
            <div className="markdown-body">{data.overview.summary || data.overview.body?.slice(0, 300)}...</div>
            <Link to={`/library/overview`} className="btn btn-sm">閱讀完整課綱 →</Link>
          </div>
        </section>
      )}

      {!hasData && (
        <div className="lc-empty">
          <div className="lc-empty-icon">📚</div>
          <p>知識庫尚未建立</p>
          <p className="text-dim">請先執行 <code>npm run build:knowledge</code> 或從 YouTube/HyRead 匯入內容</p>
        </div>
      )}

      {filtered && (
        <>
          {filtered.principles.length > 0 && (
            <section className="lc-section">
              <h2 className="lc-section-title">
                <RouteIcon to="/skills" size={18} /> 心法原則 ({filtered.principles.length})
              </h2>
              <div className="lc-grid">
                {filtered.principles.map(p => <PrincipleCard key={p.id} p={p} query={query} />)}
              </div>
            </section>
          )}

          {filtered.categories.length > 0 && (
            <section className="lc-section">
              <h2 className="lc-section-title">
                <RouteIcon to="/" size={18} /> 學習分類 ({filtered.categories.length})
              </h2>
              <div className="lc-grid">
                {filtered.categories.map(c => <NoteCard key={c.id} note={c} kind="category" query={query} />)}
              </div>
            </section>
          )}

          {filtered.cases.length > 0 && (
            <section className="lc-section">
              <h2 className="lc-section-title">
                <RouteIcon to="/skills" size={18} /> 案例講解 ({filtered.cases.length})
              </h2>
              <div className="lc-grid">
                {filtered.cases.map(c => <NoteCard key={c.id} note={c} kind="case" query={query} />)}
              </div>
            </section>
          )}

          {filtered.index.length > 0 && (
            <section className="lc-section">
              <h2 className="lc-section-title">
                <RouteIcon to="/" size={18} /> 名詞 · 公司 · 單集 ({filtered.index.length})
              </h2>
              <div className="lc-index-list">
                {filtered.index.slice(0, 100).map((item, i) => (
                  <IndexItemRow key={`${item.kind}:${item.id}:${i}`} item={item} query={query} />
                ))}
                {filtered.index.length > 100 && (
                  <div className="text-dim">...還有 {filtered.index.length - 100} 項</div>
                )}
              </div>
            </section>
          )}

          {!filtered.principles.length && !filtered.categories.length && !filtered.cases.length && !filtered.index.length && query && (
            <div className="lc-empty">
              <p>搜尋「{query}」沒有結果</p>
            </div>
          )}
        </>
      )}

      {data?.counts && (
        <section className="lc-section lc-stats">
          <h2 className="lc-section-title">知識庫統計</h2>
          <div className="lc-stat-grid">
            {Object.entries(data.counts).map(([k, v]) => (
              <div key={k} className="lc-stat-card">
                <div className="lc-stat-num">{v}</div>
                <div className="lc-stat-label">{TYPE_LABELS[k] || k}</div>
              </div>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}
