"use client";

import { useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import {
  ReactFlow,
  Background,
  BackgroundVariant,
  Controls,
  MiniMap,
  type Node,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { LessonNode } from "./nodes/lesson-node";
import { TextbookContentNode as TextbookContentNodeComponent } from "./nodes/textbook-content-node";
import { toRfNodes, toRfEdges } from "../lib/rf-mappers";
import { getNodeColor } from "../lib/node-summary";
import { useMediaQuery } from "@/shared/hooks/use-media-query";
import { LessonPlanMobileView } from "./lesson-plan-mobile-view";
import type { LessonPlanDocument } from "../types";

const nodeTypes = {
  lesson: LessonNode,
  textbook_content: TextbookContentNodeComponent,
};

interface Props {
  doc: LessonPlanDocument;
  textbookTitle?: string;
  chapterTitle?: string;
}

/**
 * 只读课案画布视图（学生/家长/管理员/教研组长使用）。
 *
 * 复用 React Flow 渲染，但禁用所有编辑交互：
 * - 节点不可拖动、不可连线
 * - 可缩放、可平移（便于查看）
 * - 可点击节点查看详情（通过 onSelectNode 回调）
 */
export function LessonPlanReadonlyView({ doc, textbookTitle, chapterTitle }: Props) {
  const t = useTranslations("lessonPreparation");
  const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
  // V5-13 P3：小屏设备使用线性移动视图替代画布
  const isMobile = useMediaQuery("(max-width: 768px)");

  const rfNodes = useMemo(() => toRfNodes(doc.nodes, selectedNodeId), [doc.nodes, selectedNodeId]);
  const rfEdges = useMemo(
    () => toRfEdges(doc.edges, selectedNodeId, doc.anchors ?? [], doc.nodes),
    [doc.edges, doc.anchors, selectedNodeId, doc.nodes],
  );

  // 为正文节点准备 data（锚点、选中节点、选择回调）
  const nodesWithData: Node[] = useMemo(() => {
    return rfNodes.map((n) => {
      if (n.type === "textbook_content") {
        return {
          ...n,
          data: {
            ...n.data,
            node: doc.nodes.find((nn) => nn.id === n.id),
            anchors: doc.anchors ?? [],
            selectedNodeId,
            onSelectNode: setSelectedNodeId,
          },
        };
      }
      return n;
    });
  }, [rfNodes, doc.nodes, doc.anchors, selectedNodeId]);

  // V5-13 P3：移动端渲染线性视图
  if (isMobile) {
    return (
      <LessonPlanMobileView doc={doc} textbookTitle={textbookTitle} chapterTitle={chapterTitle} />
    );
  }

  return (
    <div className="h-full w-full relative">
      {/* 顶部信息条 */}
      {(textbookTitle || chapterTitle) && (
        <div className="absolute top-2 left-2 z-10 bg-surface/95 backdrop-blur border border-outline-variant rounded-md px-3 py-1.5 text-xs text-on-surface-variant flex items-center gap-2 shadow-sm">
          {textbookTitle && (
            <span className="flex items-center gap-1">
              <span className="font-medium">{t("editor.textbookLabel")}</span>
              {textbookTitle}
            </span>
          )}
          {chapterTitle && (
            <span className="flex items-center gap-1">
              <span className="font-medium">{t("editor.chapterLabel")}</span>
              {chapterTitle}
            </span>
          )}
        </div>
      )}

      <ReactFlow
        nodes={nodesWithData}
        edges={rfEdges}
        nodeTypes={nodeTypes}
        nodesDraggable={false}
        nodesConnectable={false}
        elementsSelectable={true}
        panOnDrag={true}
        zoomOnScroll={true}
        zoomOnPinch={true}
        panOnScroll={false}
        zoomOnDoubleClick={false}
        selectionOnDrag={false}
        fitView
        fitViewOptions={{ padding: 0.2 }}
        proOptions={{ hideAttribution: true }}
      >
        <Background variant={BackgroundVariant.Dots} gap={12} size={1} />
        <Controls showInteractive={false} />
        <MiniMap
          pannable
          zoomable
          nodeColor={(n) => {
            // V3 修复：使用 getNodeColor 替代硬编码颜色，与编辑器保持一致
            const data = n.data;
            if (!data || typeof data !== "object") return getNodeColor(n.type ?? "");
            const nodeData = data.node;
            if (
              nodeData &&
              typeof nodeData === "object" &&
              nodeData !== null &&
              "type" in nodeData &&
              typeof nodeData.type === "string"
            ) {
              return getNodeColor(nodeData.type);
            }
            return getNodeColor(n.type ?? "");
          }}
        />
      </ReactFlow>
    </div>
  );
}
