"use client";

import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Placeholder from "@tiptap/extension-placeholder";
import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import type { RichTextBlockData } from "../../types";
import { KnowledgePointPicker } from "../knowledge-point-picker";
import { Tag } from "lucide-react";

interface Props {
  data: RichTextBlockData;
  hint?: string;
  textbookId?: string;
  chapterId?: string;
  onUpdate: (data: RichTextBlockData) => void;
}

export function RichTextBlock({
  data,
  hint,
  textbookId,
  chapterId,
  onUpdate,
}: Props) {
  const t = useTranslations("lessonPreparation");
  const editor = useEditor({
    extensions: [
      StarterKit,
      Placeholder.configure({ placeholder: hint ?? t("richText.placeholder") }),
    ],
    content: data.html,
    immediatelyRender: false,
    onUpdate: ({ editor }) => {
      onUpdate({ ...data, html: editor.getHTML() });
    },
    editorProps: {
      attributes: {
        class:
          "prose prose-sm max-w-none focus:outline-none min-h-[60px] px-3 py-2",
      },
    },
  });

  // 外部 content 变化时同步（如版本回退）
  useEffect(() => {
    if (editor && !editor.isDestroyed && data.html !== editor.getHTML()) {
      editor.commands.setContent(data.html);
    }
  }, [data.html, editor]);

  const [showKpPicker, setShowKpPicker] = useState(false);

  return (
    <div>
      <EditorContent editor={editor} />
      <div className="flex items-center gap-2 mt-2 px-3 flex-wrap">
        {data.knowledgePointIds.length > 0 && (
          <span className="text-xs text-on-surface-variant">
            {t("knowledgePoint.linked", { count: data.knowledgePointIds.length })}
          </span>
        )}
        <button
          onClick={() => setShowKpPicker(true)}
          className="text-xs text-primary hover:underline inline-flex items-center gap-1"
        >
          <Tag className="w-3 h-3" />
          {t("knowledgePoint.annotate")}
        </button>
      </div>
      {showKpPicker && (
        <KnowledgePointPicker
          textbookId={textbookId}
          chapterId={chapterId}
          selectedIds={data.knowledgePointIds}
          onChange={(ids) => onUpdate({ ...data, knowledgePointIds: ids })}
          onClose={() => setShowKpPicker(false)}
        />
      )}
    </div>
  );
}
