"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> {
    groupBlock: {
      /** 插入大题分组(如"一、选择题") */
      insertGroup: (title?: string, instruction?: string) => ReturnType
      /** 将当前选区内容包裹为大题分组 */
      wrapInGroup: (title?: string, instruction?: string) => ReturnType
    }
  }
}

const GroupView = ({ node, updateAttributes }: NodeViewProps) => {
  const t = useTranslations("examHomework")
  const title = (node.attrs.title as string) || ""
  const instruction = (node.attrs.instruction as string) || ""
  const stats = countQuestionsAndScore(node.toJSON())

  return (
    <NodeViewWrapper className="my-4 rounded-md border-l-4 border-l-primary bg-primary/5 p-3">
      <div className="mb-1 flex flex-wrap items-center gap-2">
        <input
          type="text"
          value={title}
          onChange={(e) => updateAttributes({ title: e.target.value })}
          placeholder={t("exam.editorExtensions.group.titlePlaceholder")}
          className="flex-1 bg-transparent text-base font-semibold focus:outline-none"
        />
        <span className="rounded bg-primary/10 px-2 py-0.5 text-xs text-primary">
          {t("exam.editorExtensions.group.statsSummary", { count: stats.count, score: stats.score })}
        </span>
      </div>
      <input
        type="text"
        value={instruction}
        onChange={(e) => updateAttributes({ instruction: e.target.value })}
        placeholder={t("exam.editorExtensions.group.instructionPlaceholder")}
        className="mb-2 w-full bg-transparent text-xs text-muted-foreground focus:outline-none"
      />
      <NodeViewContent className="mt-1 block" />
    </NodeViewWrapper>
  )
}

/**
 * 大题分组节点 —— 如"一、选择题""二、填空题"。
 * 不是题目,题数和总分由内部子题自动累加。
 * instruction 字段用于"每小题3分"等说明,不影响统计。
 */
export const GroupBlock = Node.create({
  name: "groupBlock",
  group: "block",
  content: "block+",
  defining: true,
  isolating: true,
  addAttributes() {
    return {
      title: { default: "" },
      instruction: { default: "" },
    }
  },
  parseHTML: () => [{ tag: "div[data-group-block]" }],
  renderHTML: ({ HTMLAttributes }) => [
    "div",
    mergeAttributes(HTMLAttributes, { "data-group-block": "true" }),
    0,
  ],
  addNodeView() {
    return ReactNodeViewRenderer(GroupView)
  },
  addCommands() {
    return {
      insertGroup:
        (title, instruction) =>
        ({ commands }) =>
          commands.insertContent({
            type: "groupBlock",
            attrs: { title: title || "", instruction: instruction || "" },
            content: [
              {
                type: "paragraph",
                content: [{ type: "text", text: " " }],
              },
            ],
          }),
      wrapInGroup:
        (title, instruction) =>
        ({ commands }) =>
          commands.wrapIn("groupBlock", {
            title: title || "",
            instruction: instruction || "",
          }),
    }
  },
})
