"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Sparkles, ChevronDown, ChevronUp } from "lucide-react";
import { useLessonPlanEditor } from "../hooks/use-lesson-plan-editor";
import { BlockRenderer } from "../config/block-registry";
import { LessonPlanErrorBoundary } from "./lesson-plan-error-boundary";
import { Button } from "@/shared/components/ui/button";
import { Trash2, X } from "lucide-react";
import { AiLessonContentGenerator } from "@/modules/ai/components/ai-lesson-content-generator";
import { useAiClientOptional } from "@/modules/ai/context/ai-client-provider";

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

export function NodeEditPanel({ textbookId, chapterId, classes }: Props) {
  const t = useTranslations("lessonPreparation");
  const tAi = useTranslations("ai");
  const { doc, selectedNodeId, updateNode, removeNode, selectNode } =
    useLessonPlanEditor();
  const aiClient = useAiClientOptional();
  const [showAiPanel, setShowAiPanel] = useState(false);

  const node = doc.nodes.find((n) => n.id === selectedNodeId);

  if (!node) {
    return (
      <div className="h-full flex items-center justify-center text-on-surface-variant text-sm p-4">
        {t("editor.selectNodeHint")}
      </div>
    );
  }

  // 正文节点不在侧边面板编辑（直接在画布上交互）
  if (node.type === "textbook_content") {
    return (
      <div className="h-full flex flex-col border-l border-outline-variant bg-surface">
        <div className="flex items-center gap-2 px-4 py-2 border-b border-outline-variant">
          <span className="flex-1 font-title-md text-title-md">
            {t("editor.textbookContent")}
          </span>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => selectNode(null)}
            aria-label={t("action.close")}
          >
            <X className="w-4 h-4" aria-hidden="true" />
          </Button>
        </div>
        <div className="flex-1 overflow-y-auto p-4 text-sm text-on-surface-variant">
          {t("editor.textbookContentEmpty")}
        </div>
      </div>
    );
  }

  // 教学节点：通过类型守卫收窄为 LessonPlanNode
  const lessonNode = node as import("../types").LessonPlanNode;

  // 从节点标题提取主题用于 AI 内容生成
  const aiTopic = lessonNode.title || t("editor.textbookContent");

  return (
    <div className="h-full flex flex-col border-l border-outline-variant bg-surface">
      {/* 面板头部 */}
      <div className="flex items-center gap-2 px-4 py-2 border-b border-outline-variant">
        <input
          value={lessonNode.title}
          onChange={(e) => updateNode(lessonNode.id, { title: e.target.value })}
          className="flex-1 bg-transparent font-title-md text-title-md focus:outline-none"
          aria-label={lessonNode.title}
        />
        <Button
          variant="ghost"
          size="sm"
          onClick={() => selectNode(null)}
          aria-label={t("action.close")}
        >
          <X className="w-4 h-4" aria-hidden="true" />
        </Button>
      </div>

      {/* 内容编辑区 - 使用 Error Boundary 包裹 + BlockRenderer 配置驱动渲染 */}
      <div className="flex-1 overflow-y-auto p-3">
        <LessonPlanErrorBoundary>
          <BlockRenderer
            type={lessonNode.type}
            blockId={lessonNode.id}
            data={lessonNode.data}
            textbookId={textbookId}
            chapterId={chapterId}
            classes={classes}
            onUpdate={(d) => updateNode(lessonNode.id, { data: d })}
          />
          {/* BlockRenderer 返回 null 时显示未知类型提示 */}
          <UnknownBlockHint type={lessonNode.type} t={t} />
        </LessonPlanErrorBoundary>

        {/* AI 内容生成区（可折叠） */}
        {aiClient ? (
          <div className="mt-4 border-t border-outline-variant pt-3">
            <Button
              variant="ghost"
              size="sm"
              className="w-full justify-between"
              onClick={() => setShowAiPanel(!showAiPanel)}
              aria-expanded={showAiPanel}
            >
              <span className="flex items-center gap-1">
                <Sparkles className="w-3.5 h-3.5 text-primary" />
                {tAi("lessonPrep.generateContent")}
              </span>
              {showAiPanel ? (
                <ChevronUp className="w-3.5 h-3.5" />
              ) : (
                <ChevronDown className="w-3.5 h-3.5" />
              )}
            </Button>
            {showAiPanel ? (
              <div className="mt-2">
                <AiLessonContentGenerator
                  topic={aiTopic}
                  textbookId={textbookId}
                  chapterId={chapterId}
                />
              </div>
            ) : null}
          </div>
        ) : null}
      </div>

      {/* 底部操作 */}
      <div className="px-4 py-2 border-t border-outline-variant">
        <Button
          variant="outline"
          size="sm"
          className="text-error"
          onClick={() => removeNode(lessonNode.id)}
        >
          <Trash2 className="w-3 h-3 mr-1" aria-hidden="true" />
          {t("action.delete")}
        </Button>
      </div>
    </div>
  );
}

/**
 * 未知 Block 类型提示（配置驱动，当 BlockRenderer 返回 null 时显示）。
 * 独立组件避免在主组件中条件渲染。
 */
function UnknownBlockHint({
  type,
  t,
}: {
  type: string;
  t: ReturnType<typeof useTranslations>;
}) {
  // 已知类型不显示提示
  const knownTypes = [
    "objective", "key_point", "import", "new_teaching", "consolidation",
    "summary", "homework", "blackboard", "rich_text", "exercise",
    "text_study", "reflection",
  ];
  if (knownTypes.includes(type)) {
    return null;
  }
  return (
    <div className="text-on-surface-variant text-sm p-4">
      {t("editor.unknownBlockType")}
    </div>
  );
}
