"use client";

/**
 * 章节目录页（ai14，P4）
 *
 * - 消费 useChapters 查询（textbookId 取自动态路由参数）
 * - 树形导航（可展开/收起），mark-left 竖线样式
 * - 每个章节：标题、层级、顺序号
 */

import { useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useChapters } from "@/lib/graphql/hooks";
import type { ChapterNode as ChapterNodeType } from "@/lib/graphql/types";

interface ChapterRowProps {
  chapter: ChapterNodeType;
  level: number;
}

function ChapterRow({ chapter, level }: ChapterRowProps): React.ReactNode {
  const hasChildren = chapter.children && chapter.children.length > 0;
  const [expanded, setExpanded] = useState(level === 0);

  return (
    <li
      className="mark-left"
      style={{ marginLeft: level > 0 ? "var(--space-md)" : 0 }}
    >
      <div className="py-sm">
        <div className="flex items-center justify-between gap-md">
          <div className="flex items-center gap-sm min-w-0">
            {hasChildren ? (
              <button
                type="button"
                className="text-xs text-accent"
                onClick={() => setExpanded((v) => !v)}
                aria-expanded={expanded}
                aria-label={expanded ? "收起" : "展开"}
              >
                {expanded ? "▼" : "▶"}
              </button>
            ) : (
              <span className="text-xs text-ink-subtle" aria-hidden="true">
                •
              </span>
            )}
            <span className="text-sm text-ink text-truncate">
              {chapter.name}
            </span>
          </div>
          <div className="flex items-center gap-sm shrink-0">
            <span className="text-xs text-ink-subtle">L{chapter.level}</span>
            <span className="text-xs text-ink-subtle">#{chapter.order}</span>
          </div>
        </div>
      </div>

      {hasChildren && expanded ? (
        <ul className="mt-xs space-y-xs" role="group">
          {(chapter.children ?? []).map((child: ChapterNodeType) => (
            <ChapterRow key={child.id} chapter={child} level={level + 1} />
          ))}
        </ul>
      ) : null}
    </li>
  );
}

export default function ChaptersPage(): React.ReactNode {
  const params = useParams();
  const textbookId =
    typeof params.id === "string"
      ? params.id
      : Array.isArray(params.id)
        ? (params.id[0] ?? "")
        : "";

  const { data, fetching, error, reexecute } = useChapters(textbookId);
  const chapters = data ?? [];

  return (
    <main
      className="px-md py-lg max-w-4xl mx-auto"
      aria-labelledby="chapters-title"
    >
      <header className="mb-lg">
        <div className="flex items-center gap-sm">
          <Link href="/textbooks" className="text-sm text-accent">
            ← 教材列表
          </Link>
        </div>
        <h1 id="chapters-title" className="font-serif text-2xl text-ink mt-sm">
          章节目录
        </h1>
        <p className="mt-xs text-sm text-ink-muted">教材章节与课时</p>
      </header>

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

      {fetching ? (
        <p className="text-sm text-ink-muted" aria-live="polite">
          加载中…
        </p>
      ) : error ? (
        <div className="mark-left py-md px-md mb-md" aria-live="assertive">
          <p className="text-sm text-ink">{error.message || "加载失败"}</p>
          <button
            type="button"
            className="btn-secondary mt-sm"
            onClick={() => reexecute()}
          >
            重试
          </button>
        </div>
      ) : chapters.length === 0 ? (
        <p className="text-sm text-ink-muted" role="status">
          暂无章节
        </p>
      ) : (
        <ul className="space-y-xs" role="tree" aria-label="章节树">
          {chapters.map((ch: ChapterNodeType) => (
            <ChapterRow key={ch.id} chapter={ch} level={0} />
          ))}
        </ul>
      )}
    </main>
  );
}
