"use client"

import { Node, mergeAttributes } from "@tiptap/core"
import { ReactNodeViewRenderer, NodeViewWrapper, NodeViewContent, type NodeViewProps } from "@tiptap/react"
import { useTranslations } from "next-intl"
import { countQuestionsAndScore } from "../utils/count-questions"

declare module "@tiptap/core" {
  interface Commands<ReturnType> {
    sectionBlock: {
      /** 插入试卷分卷(如"第Ⅰ卷 选择题") */
      insertSection: (title?: string, level?: number) => ReturnType
      /** 将当前选区内容包裹为试卷分卷 */
      wrapInSection: (title?: string, level?: number) => ReturnType
    }
  }
}

const SectionView = ({ node, updateAttributes }: NodeViewProps) => {
  const t = useTranslations("examHomework")
  const title = (node.attrs.title as string) || ""
  const level = typeof node.attrs.level === "number" ? node.attrs.level : 1
  const stats = countQuestionsAndScore(node.toJSON())

  const titleSize = level === 1 ? "text-lg" : "text-base"

  return (
    <NodeViewWrapper className="my-4 rounded-md border-2 border-primary/40 bg-primary/5 p-4">
      <div className="mb-2 flex flex-wrap items-center gap-2 border-b border-primary/20 pb-2">
        <input
          type="text"
          value={title}
          onChange={(e) => updateAttributes({ title: e.target.value })}
          placeholder={t("exam.editorExtensions.section.titlePlaceholder")}
          className={`flex-1 bg-transparent font-bold focus:outline-none ${titleSize}`}
        />
        <select
          value={String(level)}
          onChange={(e) => updateAttributes({ level: Number(e.target.value) })}
          className="rounded border bg-background px-1.5 py-0.5 text-xs"
          title={t("exam.editorExtensions.section.levelTitle")}
        >
          <option value="1">{t("exam.editorExtensions.section.levelVolume")}</option>
          <option value="2">{t("exam.editorExtensions.section.levelPart")}</option>
          <option value="3">{t("exam.editorExtensions.section.levelSubVolume")}</option>
        </select>
        <span className="rounded bg-primary/10 px-2 py-0.5 text-xs text-primary">
          {t("exam.editorExtensions.section.statsSummary", { count: stats.count, score: stats.score })}
        </span>
      </div>
      <NodeViewContent className="mt-2 block" />
    </NodeViewWrapper>
  )
}

/**
 * 试卷分卷节点 —— 顶层结构,如"第Ⅰ卷 选择题(共24分)"。
 * 不是题目,题数和总分由内部子题自动累加。
 * 可嵌套 groupBlock(大题)和 questionBlock(题目)。
 */
export const SectionBlock = Node.create({
  name: "sectionBlock",
  group: "block",
  content: "block+",
  defining: true,
  isolating: true,
  addAttributes() {
    return {
      title: { default: "" },
      level: { default: 1 },
    }
  },
  parseHTML: () => [{ tag: "div[data-section-block]" }],
  renderHTML: ({ HTMLAttributes }) => [
    "div",
    mergeAttributes(HTMLAttributes, { "data-section-block": "true" }),
    0,
  ],
  addNodeView() {
    return ReactNodeViewRenderer(SectionView)
  },
  addCommands() {
    return {
      insertSection:
        (title, level) =>
        ({ commands }) =>
          commands.insertContent({
            type: "sectionBlock",
            attrs: { title: title || "", level: level ?? 1 },
            content: [
              {
                type: "paragraph",
                content: [{ type: "text", text: " " }],
              },
            ],
          }),
      wrapInSection:
        (title, level) =>
        ({ commands }) =>
          commands.wrapIn("sectionBlock", {
            title: title || "",
            level: level ?? 1,
          }),
    }
  },
})
