"use client";

/**
 * 教材阅读器 - 章节树 + 内容 + 阅读设置
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL TextbookDetailQuery：教材详情（章节树 + 知识点列表）
 *
 * 布局：左侧章节树（可展开/折叠）+ 中间章节内容（简单 markdown 渲染）+ 右侧设置面板
 * 导航："上一章"/"下一章" 按钮切换章节
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, useMemo, useCallback } from "react";
import { useQuery } from "urql";
import { useParams } from "next/navigation";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { TextbookDetailQuery } from "@/lib/graphql-p7-exams";
import type { TextbookChapter, TextbookDetail } from "@/lib/graphql-p7-exams";

/** 阅读设置 */
interface ReaderSettings {
  fontSize: "small" | "medium" | "large";
  lineHeight: "compact" | "normal" | "loose";
  theme: "default" | "warm";
}

/** 字号映射到 Tailwind class */
const FONT_SIZE_CLASS: Record<ReaderSettings["fontSize"], string> = {
  small: "text-sm",
  medium: "text-base",
  large: "text-lg",
};

/** 行高映射到 Tailwind class */
const LINE_HEIGHT_CLASS: Record<ReaderSettings["lineHeight"], string> = {
  compact: "leading-tight",
  normal: "leading-normal",
  loose: "leading-loose",
};

/** 主题映射到 Tailwind class */
const THEME_CLASS: Record<ReaderSettings["theme"], string> = {
  default: "bg-paper text-ink",
  warm: "bg-subtle text-ink",
};

/** 默认设置 */
const DEFAULT_SETTINGS: ReaderSettings = {
  fontSize: "medium",
  lineHeight: "normal",
  theme: "default",
};

/** 渲染简单 markdown：## 标题 + 段落 */
function renderChapterContent(
  content: string,
  fontSizeClass: string,
  lineHeightClass: string,
): React.ReactNode {
  const lines = content.split("\n");
  const blocks: React.ReactNode[] = [];
  let currentHeading: string | null = null;
  let currentParagraph: string[] = [];

  const flushParagraph = (key: string) => {
    if (currentParagraph.length > 0) {
      blocks.push(
        <p
          key={`p-${key}`}
          className={`mb-4 ${fontSizeClass} ${lineHeightClass}`}
        >
          {currentParagraph.join(" ")}
        </p>,
      );
      currentParagraph = [];
    }
  };

  lines.forEach((line, i) => {
    const trimmed = line.trim();
    if (trimmed.startsWith("# ")) {
      // H1：章节主标题（已在 header 展示，跳过）
      flushParagraph(`f${i}`);
    } else if (trimmed.startsWith("## ")) {
      // H2：小节标题
      flushParagraph(`f${i}`);
      currentHeading = trimmed.slice(3);
      blocks.push(
        <h3
          key={`h-${i}`}
          className={`mt-6 mb-3 font-serif text-ink ${fontSizeClass === "text-sm" ? "text-base" : fontSizeClass === "text-base" ? "text-lg" : "text-xl"}`}
        >
          {currentHeading}
        </h3>,
      );
      currentHeading = null;
    } else if (trimmed === "") {
      // 空行：段落分隔
      flushParagraph(`f${i}`);
    } else {
      currentParagraph.push(trimmed);
    }
  });
  flushParagraph("f-end");

  return blocks;
}

export default function TextbookReaderPage(): React.ReactNode {
  const params = useParams<{ id: string }>();
  const textbookId = params?.id ?? "";

  const [result] = useQuery({
    query: TextbookDetailQuery,
    variables: { id: textbookId },
    pause: !textbookId,
  });

  const textbook: TextbookDetail | undefined =
    (result.data?.textbookDetail as TextbookDetail | undefined) ?? undefined;

  // === 阅读状态 ===
  const [currentChapterIdx, setCurrentChapterIdx] = useState(0);
  const [expandedChapters, setExpandedChapters] = useState<Set<string>>(
    new Set(),
  );
  const [settings, setSettings] = useState<ReaderSettings>(DEFAULT_SETTINGS);
  const [settingsOpen, setSettingsOpen] = useState(false);

  const chapters: TextbookChapter[] = textbook?.chapters ?? [];

  // 当前章节（安全访问）
  const currentChapter: TextbookChapter | null =
    chapters[currentChapterIdx] ?? null;

  // 章节切换
  const goToChapter = useCallback(
    (idx: number) => {
      if (idx >= 0 && idx < chapters.length) {
        setCurrentChapterIdx(idx);
      }
    },
    [chapters.length],
  );

  const goPrev = useCallback(() => {
    setCurrentChapterIdx((i) => Math.max(0, i - 1));
  }, []);

  const goNext = useCallback(() => {
    setCurrentChapterIdx((i) => Math.min(chapters.length - 1, i + 1));
  }, [chapters.length]);

  // 展开/折叠章节
  const toggleChapter = useCallback((chapterId: string) => {
    setExpandedChapters((prev) => {
      const next = new Set(prev);
      if (next.has(chapterId)) {
        next.delete(chapterId);
      } else {
        next.add(chapterId);
      }
      return next;
    });
  }, []);

  // 当前章节内容渲染
  const renderedContent = useMemo(() => {
    if (!currentChapter) return null;
    return renderChapterContent(
      currentChapter.content,
      FONT_SIZE_CLASS[settings.fontSize],
      LINE_HEIGHT_CLASS[settings.lineHeight],
    );
  }, [currentChapter, settings.fontSize, settings.lineHeight]);

  return (
    <div className="flex h-screen bg-paper">
      {/* 左侧：章节树 */}
      <aside className="w-64 flex-shrink-0 border-r border-rule bg-paper flex flex-col overflow-hidden">
        <div className="px-6 py-6 flex-shrink-0">
          <Link
            href="/textbooks"
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
          >
            ← 返回教材列表
          </Link>
          <h1 className="mt-2 text-lg font-serif text-ink">
            {textbook?.title ?? "加载中..."}
          </h1>
          <p className="mt-1 text-tiny text-ink-muted">
            {textbook?.subject} · {textbook?.grade} · {textbook?.version}
          </p>
        </div>
        <div className="rule-thin mx-6" />

        <nav className="flex-1 overflow-y-auto px-3 py-4">
          {result.fetching ? (
            <Loading lines={4} />
          ) : chapters.length === 0 ? (
            <p className="px-3 py-2 text-tiny text-ink-muted">暂无章节</p>
          ) : (
            chapters.map((ch, idx) => {
              const isExpanded = expandedChapters.has(ch.id);
              const isActive = idx === currentChapterIdx;
              return (
                <div key={ch.id} className="mb-1">
                  <div className="flex items-center">
                    <button
                      type="button"
                      onClick={() => toggleChapter(ch.id)}
                      className="flex-shrink-0 px-1 py-1 text-tiny text-ink-muted hover:opacity-70"
                      aria-label={isExpanded ? "折叠" : "展开"}
                    >
                      {isExpanded ? "▾" : "▸"}
                    </button>
                    <button
                      type="button"
                      onClick={() => goToChapter(idx)}
                      className={`flex-1 text-left px-2 py-1.5 text-sm transition-colors ${
                        isActive
                          ? "text-accent border-l-2 border-accent font-serif"
                          : "text-ink border-l-2 border-transparent font-sans hover:text-accent"
                      }`}
                    >
                      {ch.title}
                    </button>
                  </div>
                  {isExpanded && ch.knowledgePoints.length > 0 && (
                    <ul className="ml-6 mt-1 mb-2 space-y-1">
                      {ch.knowledgePoints.map((kp) => (
                        <li
                          key={kp.id}
                          className="text-tiny text-ink-muted px-2 py-0.5"
                        >
                          {kp.name}
                        </li>
                      ))}
                    </ul>
                  )}
                </div>
              );
            })
          )}
        </nav>
      </aside>

      {/* 中间：章节内容 */}
      <main className="flex-1 overflow-y-auto">
        {result.fetching ? (
          <div className="px-10 py-10">
            <Loading lines={8} />
          </div>
        ) : result.error ? (
          <div className="px-10 py-10">
            <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>
          </div>
        ) : !textbook ? (
          <div className="px-10 py-10">
            <Empty title="教材不存在" description="可能已被删除或链接无效" />
          </div>
        ) : !currentChapter ? (
          <div className="px-10 py-10">
            <Empty title="暂无章节" description="该教材尚未添加章节内容" />
          </div>
        ) : (
          <div className="px-10 py-10 max-w-3xl mx-auto">
            {/* 章节标题 */}
            <header className="mb-8">
              <p className="text-tiny uppercase tracking-wide text-ink-muted">
                第 {currentChapterIdx + 1} / {chapters.length} 章
              </p>
              <h2 className="mt-1 text-3xl font-serif text-ink">
                {currentChapter.title}
              </h2>
            </header>

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

            {/* 章节正文 */}
            <article
              className={`prose-sm rounded-card p-6 ${THEME_CLASS[settings.theme]}`}
            >
              {renderedContent}
            </article>

            {/* 知识点列表 */}
            {currentChapter.knowledgePoints.length > 0 && (
              <section className="mt-8">
                <h3 className="text-base font-serif text-ink mb-3">
                  本章知识点
                </h3>
                <ul className="space-y-2">
                  {currentChapter.knowledgePoints.map((kp, i) => (
                    <li
                      key={kp.id}
                      className="flex items-baseline gap-2 text-sm text-ink"
                    >
                      <span className="font-mono text-tiny text-ink-muted">
                        {String(i + 1).padStart(2, "0")}
                      </span>
                      <span>{kp.name}</span>
                      {kp.description && (
                        <span className="text-tiny text-ink-muted">
                          — {kp.description}
                        </span>
                      )}
                    </li>
                  ))}
                </ul>
              </section>
            )}

            {/* 导航按钮 */}
            <nav className="mt-10 flex items-center justify-between border-t border-rule pt-6">
              <button
                type="button"
                onClick={goPrev}
                disabled={currentChapterIdx <= 0}
                className="px-4 py-2 text-sm text-ink border border-rule rounded-button disabled:opacity-30 hover:bg-subtle"
              >
                ← 上一章
              </button>
              <span className="text-tiny text-ink-muted">
                {currentChapterIdx + 1} / {chapters.length}
              </span>
              <button
                type="button"
                onClick={goNext}
                disabled={currentChapterIdx >= chapters.length - 1}
                className="px-4 py-2 text-sm text-ink border border-rule rounded-button disabled:opacity-30 hover:bg-subtle"
              >
                下一章 →
              </button>
            </nav>
          </div>
        )}
      </main>

      {/* 右侧：设置面板（可切换显示/隐藏） */}
      <aside
        className={`w-56 flex-shrink-0 border-l border-rule bg-paper flex flex-col transition-all ${
          settingsOpen ? "opacity-100" : "opacity-0 pointer-events-none w-0"
        }`}
      >
        <div className="px-6 py-6 flex-shrink-0">
          <h2 className="text-base font-serif text-ink">阅读设置</h2>
        </div>
        <div className="rule-thin mx-6" />
        <div className="flex-1 px-6 py-4 space-y-6 overflow-y-auto">
          {/* 字体大小 */}
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-2">
              字体大小
            </label>
            <div className="flex gap-2">
              {(["small", "medium", "large"] as const).map((size) => (
                <button
                  key={size}
                  type="button"
                  onClick={() =>
                    setSettings((s) => ({ ...s, fontSize: size }))
                  }
                  className={`px-3 py-1 text-tiny rounded-button border ${
                    settings.fontSize === size
                      ? "border-accent text-accent"
                      : "border-rule text-ink-muted hover:bg-subtle"
                  }`}
                >
                  {size === "small" ? "小" : size === "medium" ? "中" : "大"}
                </button>
              ))}
            </div>
          </div>

          {/* 行高 */}
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-2">
              行高
            </label>
            <div className="flex gap-2">
              {(["compact", "normal", "loose"] as const).map((lh) => (
                <button
                  key={lh}
                  type="button"
                  onClick={() =>
                    setSettings((s) => ({ ...s, lineHeight: lh }))
                  }
                  className={`px-3 py-1 text-tiny rounded-button border ${
                    settings.lineHeight === lh
                      ? "border-accent text-accent"
                      : "border-rule text-ink-muted hover:bg-subtle"
                  }`}
                >
                  {lh === "compact" ? "紧凑" : lh === "normal" ? "正常" : "宽松"}
                </button>
              ))}
            </div>
          </div>

          {/* 主题 */}
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-2">
              主题
            </label>
            <div className="flex gap-2">
              {(["default", "warm"] as const).map((theme) => (
                <button
                  key={theme}
                  type="button"
                  onClick={() => setSettings((s) => ({ ...s, theme }))}
                  className={`px-3 py-1 text-tiny rounded-button border ${
                    settings.theme === theme
                      ? "border-accent text-accent"
                      : "border-rule text-ink-muted hover:bg-subtle"
                  }`}
                >
                  {theme === "default" ? "默认" : "护眼"}
                </button>
              ))}
            </div>
          </div>

          {/* 重置 */}
          <button
            type="button"
            onClick={() => setSettings(DEFAULT_SETTINGS)}
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
          >
            重置为默认
          </button>
        </div>
      </aside>

      {/* 设置开关按钮（固定在右边缘） */}
      <button
        type="button"
        onClick={() => setSettingsOpen((v) => !v)}
        className="fixed right-0 top-1/2 -translate-y-1/2 px-2 py-3 bg-accent text-ink-on-accent text-tiny writing-mode-vertical rounded-l-button hover:bg-accent-hover"
        style={{ writingMode: "vertical-rl" }}
        aria-label="阅读设置"
      >
        {settingsOpen ? "收起设置" : "展开设置"}
      </button>
    </div>
  );
}
