"use client";

import { memo } from "react";
import { useTranslations } from "next-intl";
import { Handle, Position, type NodeProps } from "@xyflow/react";
import type { LessonPlanNode } from "../../types";
import { getNodeColor, getNodeSummary, type NodeSummaryT } from "../../lib/node-summary";

// P1 修复：类型守卫替代 as 断言，安全从 React Flow NodeProps.data 收窄
function isLessonNodeData(data: unknown): data is { node: LessonPlanNode } {
  if (typeof data !== "object" || data === null) return false;
  const obj = data as Record<string, unknown>;
  return (
    typeof obj.node === "object" &&
    obj.node !== null &&
    typeof (obj.node as Record<string, unknown>).type === "string"
  );
}

export const LessonNode = memo(function LessonNode({
  data,
  selected,
}: NodeProps) {
  const t = useTranslations("lessonPreparation");
  // P1 修复：使用类型守卫安全收窄，若数据形状不符则渲染空状态避免运行时崩溃
  if (!isLessonNodeData(data)) {
    return (
      <div className="rounded-lg border-2 border-outline-variant bg-surface p-3 text-xs text-on-surface-variant">
        {t("editor.unknownBlockType")}
      </div>
    );
  }
  const nodeData = data.node;
  const color = getNodeColor(nodeData.type);
  // 适配 next-intl 的 t 到 NodeSummaryT 接口
  const summaryT: NodeSummaryT = (key, values) => t(key, values);
  const summary = getNodeSummary(nodeData, summaryT);

  return (
    <div
      className="rounded-lg border-2 bg-surface shadow-md min-w-[200px] max-w-[260px] transition-shadow"
      style={{
        borderColor: selected ? "#1976d2" : color,
        boxShadow: selected ? "0 0 0 2px rgba(25,118,210,0.3)" : undefined,
      }}
    >
      <Handle
        type="target"
        position={Position.Top}
        className="!bg-on-surface !w-3 !h-3 !border-2 !border-surface"
      />
      <div
        className="px-3 py-2 rounded-t-md text-white text-xs font-medium flex items-center gap-1"
        style={{ backgroundColor: color }}
      >
        <span>{t(`blockType.${nodeData.type}`) ?? nodeData.type}</span>
      </div>
      <div className="px-3 py-2">
        <div className="text-sm font-medium text-on-surface truncate">
          {nodeData.title}
        </div>
        <div className="text-xs text-on-surface-variant mt-1">
          {summary}
        </div>
      </div>
      <Handle
        type="source"
        position={Position.Bottom}
        className="!bg-on-surface !w-3 !h-3 !border-2 !border-surface"
      />
    </div>
  );
});
