"use client"

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

export type QuestionBlockType =
  | "single_choice"
  | "multiple_choice"
  | "judgment"
  | "text"
  | "composite"

export interface QuestionBlockAttrs {
  questionId: string
  type: QuestionBlockType
  score: number
}

declare module "@tiptap/core" {
  interface Commands<ReturnType> {
    questionBlock: {
      /** 插入题目块(含题型/分值/题干) */
      insertQuestion: (attrs?: Partial<QuestionBlockAttrs>) => ReturnType
      /** 将当前选区内容包裹为题目块 */
      wrapInQuestion: (attrs?: Partial<QuestionBlockAttrs>) => ReturnType
    }
  }
}

const QuestionView = ({ node, updateAttributes }: NodeViewProps) => {
  const t = useTranslations("examHomework")
  const { type, score } = node.attrs as QuestionBlockAttrs
  return (
    <NodeViewWrapper className="my-3 rounded-md border bg-card p-3">
      <div className="mb-2 flex items-center gap-2 border-b pb-2">
        <select
          value={type}
          onChange={(e) => updateAttributes({ type: e.target.value })}
          className="rounded border bg-background px-2 py-1 text-xs"
        >
          <option value="single_choice">{t("exam.editorExtensions.question.typeSingleChoice")}</option>
          <option value="multiple_choice">{t("exam.editorExtensions.question.typeMultipleChoice")}</option>
          <option value="judgment">{t("exam.editorExtensions.question.typeJudgment")}</option>
          <option value="text">{t("exam.editorExtensions.question.typeText")}</option>
          <option value="composite">{t("exam.editorExtensions.question.typeComposite")}</option>
        </select>
        <input
          type="number"
          min={0}
          value={score}
          onChange={(e) => updateAttributes({ score: Number(e.target.value) || 0 })}
          className="w-16 rounded border bg-background px-2 py-1 text-xs"
        />
        <span className="text-xs text-muted-foreground">{t("exam.editorExtensions.question.scoreUnit")}</span>
      </div>
      <NodeViewContent className="block text-sm" />
    </NodeViewWrapper>
  )
}

/**
 * 题目块节点 —— 单道题,含题型/分值/题干。
 * 题干内容写在 NodeViewContent 中,支持富文本(加点字、填空、图片、选项列表)。
 */
export const QuestionBlock = Node.create({
  name: "questionBlock",
  group: "block",
  content: "block+",
  defining: true,
  isolating: true,
  addAttributes() {
    return {
      questionId: { default: "" },
      type: { default: "single_choice" },
      score: { default: 0 },
    }
  },
  parseHTML: () => [{ tag: "div[data-question-block]" }],
  renderHTML: ({ HTMLAttributes }) => [
    "div",
    mergeAttributes(HTMLAttributes, { "data-question-block": "true" }),
    0,
  ],
  addNodeView() {
    return ReactNodeViewRenderer(QuestionView)
  },
  addCommands() {
    return {
      insertQuestion:
        (attrs) =>
        ({ commands }) =>
          commands.insertContent({
            type: "questionBlock",
            attrs: {
              type: attrs?.type ?? "single_choice",
              score: attrs?.score ?? 0,
              questionId: attrs?.questionId ?? "",
            },
            content: [
              {
                type: "paragraph",
                content: [{ type: "text", text: " " }],
              },
            ],
          }),
      wrapInQuestion:
        (attrs) =>
        ({ commands }) =>
          commands.wrapIn("questionBlock", {
            type: attrs?.type ?? "single_choice",
            score: attrs?.score ?? 0,
            questionId: attrs?.questionId ?? "",
          }),
    }
  },
})
