"use client";

/**
 * @deprecated 已被 NodeEditor 替代，保留此文件用于向后兼容。
 * 列表式渲染器，使用新的 nodes API。
 */
import {
  DndContext,
  closestCenter,
  type DragEndEvent,
} from "@dnd-kit/core";
import {
  SortableContext,
  verticalListSortingStrategy,
  useSortable,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import {
  GripVertical,
  Trash2,
  ChevronUp,
  ChevronDown,
} from "lucide-react";
import { useLessonPlanEditor } from "../hooks/use-lesson-plan-editor";
import { RICH_TEXT_BLOCK_TYPES } from "../constants";
import { RichTextBlock } from "./blocks/rich-text-block";
import { ExerciseBlock } from "./blocks/exercise-block";
import { TextStudyBlock } from "./blocks/text-study-block";
import { ReflectionBlock } from "./blocks/reflection-block";
import type { LessonPlanNode, RichTextBlockData, ExerciseBlockData, TextStudyBlockData } from "../types";

interface BlockRendererProps {
  textbookId?: string;
  chapterId?: string;
  classes?: { id: string; name: string }[];
}

function SortableBlock({
  node,
  index,
  total,
  textbookId,
  chapterId,
  classes,
}: {
  node: LessonPlanNode;
  index: number;
  total: number;
  textbookId?: string;
  chapterId?: string;
  classes?: { id: string; name: string }[];
}) {
  const { attributes, listeners, setNodeRef, transform, transition } =
    useSortable({ id: node.id });
  const { updateNode, removeNode } = useLessonPlanEditor();

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  };

  const isRichText = RICH_TEXT_BLOCK_TYPES.includes(node.type);

  return (
    <div
      ref={setNodeRef}
      style={style}
      className="border border-outline-variant rounded-lg bg-surface-container-lowest"
    >
      <div className="flex items-center gap-2 px-3 py-2 border-b border-outline-variant bg-surface-container-low">
        <button
          {...attributes}
          {...listeners}
          className="cursor-grab active:cursor-grabbing text-outline hover:text-on-surface"
        >
          <GripVertical className="w-4 h-4" />
        </button>
        <input
          value={node.title}
          onChange={(e) => updateNode(node.id, { title: e.target.value })}
          className="flex-1 bg-transparent font-title-md text-title-md focus:outline-none"
        />
        <button
          onClick={() => updateNode(node.id, { order: index - 1 })}
          disabled={index === 0}
          className="p-1 text-outline hover:text-on-surface disabled:opacity-30"
        >
          <ChevronUp className="w-4 h-4" />
        </button>
        <button
          onClick={() => updateNode(node.id, { order: index + 1 })}
          disabled={index === total - 1}
          className="p-1 text-outline hover:text-on-surface disabled:opacity-30"
        >
          <ChevronDown className="w-4 h-4" />
        </button>
        <button
          onClick={() => removeNode(node.id)}
          className="p-1 text-error hover:text-error/80"
        >
          <Trash2 className="w-4 h-4" />
        </button>
      </div>
      <div className="p-2">
        {isRichText ? (
          <RichTextBlock
            data={node.data as RichTextBlockData}
            textbookId={textbookId}
            chapterId={chapterId}
            onUpdate={(d) => updateNode(node.id, { data: d })}
          />
        ) : node.type === "exercise" ? (
          <ExerciseBlock
            blockId={node.id}
            data={node.data as ExerciseBlockData}
            classes={classes ?? []}
          />
        ) : node.type === "text_study" ? (
          <TextStudyBlock
            blockId={node.id}
            data={node.data as TextStudyBlockData}
          />
        ) : node.type === "reflection" ? (
          <ReflectionBlock
            data={node.data as RichTextBlockData}
            onUpdate={(d) => updateNode(node.id, { data: d })}
          />
        ) : (
          <div className="text-on-surface-variant text-sm p-4">
            未知 block 类型
          </div>
        )}
      </div>
    </div>
  );
}

export function BlockRenderer({
  textbookId,
  chapterId,
  classes,
}: BlockRendererProps) {
  const { doc } = useLessonPlanEditor();

  function onDragEnd(e: DragEndEvent) {
    const { active, over } = e;
    if (!over || active.id === over.id) return;
    // 拖拽排序仅更新 order 字段，实际位置由节点图管理
    const oldIndex = doc.nodes.findIndex((b) => b.id === active.id);
    const newIndex = doc.nodes.findIndex((b) => b.id === over.id);
    if (oldIndex === -1 || newIndex === -1) return;
    // 交换 order
    const nodes = [...doc.nodes];
    const tmpOrder = nodes[oldIndex].order;
    nodes[oldIndex].order = nodes[newIndex].order;
    nodes[newIndex].order = tmpOrder;
  }

  return (
    <DndContext collisionDetection={closestCenter} onDragEnd={onDragEnd}>
      <SortableContext
        items={doc.nodes.map((b) => b.id)}
        strategy={verticalListSortingStrategy}
      >
        <div className="flex flex-col gap-4">
          {doc.nodes.map((b, i) => (
            <SortableBlock
              key={b.id}
              node={b}
              index={i}
              total={doc.nodes.length}
              textbookId={textbookId}
              chapterId={chapterId}
              classes={classes}
            />
          ))}
        </div>
      </SortableContext>
    </DndContext>
  );
}
