"use client";

/**
 * KnowledgeGraph 页面 - 知识图谱可视化
 *
 * 数据来源（P4 扩展，MSW mock）：GraphQL KnowledgeGraphQuery
 * - 支持按科目筛选（下拉选择）
 * - 纯 SVG 绘制节点关系图（不安装 d3/recharts）
 * - CSR + @next/dynamic 懒加载（ssr: false）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import dynamic from "next/dynamic";
import { useQuery } from "urql";
import { Loading, Empty } from "@edu/ui-components";
import { KnowledgeGraphQuery } from "@/lib/graphql-p4";
import type { KnowledgeGraphData } from "@/lib/graphql-p4";
import { KNOWLEDGE_SUBJECTS } from "@/mocks/fixtures/knowledge-graph";

// 懒加载 SVG 可视化组件（CSR only，避免 SSR 报 window 未定义）
const KnowledgeGraphView = dynamic(
  () => import("./KnowledgeGraphView"),
  {
    ssr: false,
    loading: () => <Loading lines={6} />,
  },
);

export default function KnowledgeGraphPage() {
  const [subject, setSubject] = useState<string>("全部");

  const [result] = useQuery({
    query: KnowledgeGraphQuery,
    variables: { subject: subject === "全部" ? null : subject },
  });

  const graph: KnowledgeGraphData | undefined = result.data?.knowledgeGraph;

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <h1 className="text-3xl font-serif text-ink">知识图谱</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL KnowledgeGraphQuery · 知识点掌握度与前置依赖（P4 扩展，MSW mock）
        </p>
      </header>

      <div className="rule-thin mb-8" />

      {/* 科目筛选 */}
      <div className="mb-6 flex items-baseline gap-3">
        <label className="text-tiny uppercase tracking-wide text-ink-muted">
          科目
        </label>
        <select
          value={subject}
          onChange={(e) => setSubject(e.target.value)}
          className="px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
        >
          {KNOWLEDGE_SUBJECTS.map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
        {graph ? (
          <span className="ml-2 text-tiny text-ink-muted">
            {graph.nodes.length} 节点 · {graph.edges.length} 依赖
          </span>
        ) : null}
      </div>

      {result.fetching ? (
        <Loading lines={6} />
      ) : result.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{result.error.message}
          </p>
        </div>
      ) : !graph || graph.nodes.length === 0 ? (
        <Empty title="暂无知识图谱数据" description="该科目尚未录入知识点" />
      ) : (
        <KnowledgeGraphView nodes={graph.nodes} edges={graph.edges} />
      )}
    </div>
  );
}
