"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { useLessonPlanEditor } from "../hooks/use-lesson-plan-editor";
import { NodeEditor } from "./node-editor";
import { NodeEditPanel, type AiContentGeneratorSlot } from "./node-edit-panel";
import { VersionHistoryDrawer } from "./version-history-drawer";
import { LessonPlanErrorBoundary } from "./lesson-plan-error-boundary";
import {
  useLessonPlanContextSafe,
  useLessonPlanTrackerSafe,
} from "../providers/lesson-plan-provider";
import type { BlockType, LessonPlanStatus } from "../types";
import { Button } from "@/shared/components/ui/button";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/shared/components/ui/alert-dialog";
import { Plus, Save, History, Book, FileText, Send, Undo2 } from "lucide-react";
import { toast } from "sonner";

interface Props {
  planId: string;
  initialTitle: string;
  initialDoc: import("../types").LessonPlanDocument;
  initialStatus?: LessonPlanStatus;
  textbookId?: string;
  chapterId?: string;
  textbookTitle?: string;
  chapterTitle?: string;
  classes?: { id: string; name: string }[];
  /** AI 内容生成器（可选，通过 props 注入避免模块耦合，P0-11 修复）*/
  aiContentGenerator?: AiContentGeneratorSlot;
}

const BLOCK_TYPES_TO_ADD: BlockType[] = [
  "objective",
  "key_point",
  "import",
  "new_teaching",
  "consolidation",
  "summary",
  "homework",
  "blackboard",
  "exercise",
  "text_study",
  "rich_text",
  "reflection",
];

export function LessonPlanEditor({
  planId,
  initialTitle,
  initialDoc,
  initialStatus = "draft",
  textbookId,
  chapterId,
  textbookTitle,
  chapterTitle,
  classes,
  aiContentGenerator,
}: Props) {
  const t = useTranslations("lessonPreparation");
  const editor = useLessonPlanEditor();
  const tracker = useLessonPlanTrackerSafe();
  const ctx = useLessonPlanContextSafe();
  const service = ctx?.service ?? null;
  const [showVersions, setShowVersions] = useState(false);
  const [showAddMenu, setShowAddMenu] = useState(false);
  const [planStatus, setPlanStatus] = useState<LessonPlanStatus>(initialStatus);
  const [publishing, setPublishing] = useState(false);
  const autoSaveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const versionTimer = useRef<ReturnType<typeof setInterval> | null>(null);
  const addMenuRef = useRef<HTMLDivElement>(null);

  // 初始化：仅在 planId 变化时 hydrate（修复 P1-3）
  const initKey = planId;
  useEffect(() => {
    useLessonPlanEditor.getState().hydrate(planId, initialTitle, initialDoc);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [initKey]);

  // 自动保存（debounce 3s）- 用 getState() 获取最新值（修复 P1-4）
  // V3 修复：完全通过 service 调用，不直接 import actions
  useEffect(() => {
    if (!editor.isDirty) return;
    if (!service) return;
    if (autoSaveTimer.current) clearTimeout(autoSaveTimer.current);
    autoSaveTimer.current = setTimeout(async () => {
      const state = useLessonPlanEditor.getState();
      state.setSaving(true);
      try {
        const res = await service.updateLessonPlan({
          planId: state.planId,
          title: state.title,
          content: state.doc,
        });
        if (res.success) state.markSaved();
      } catch (e) {
        console.error("[LessonPlanEditor] auto-save failed", e);
      } finally {
        state.setSaving(false);
      }
    }, 3000);
    return () => {
      if (autoSaveTimer.current) clearTimeout(autoSaveTimer.current);
    };
  }, [editor.isDirty, editor.doc, planId, service]);

  // 定时自动版本（30min）
  useEffect(() => {
    if (!service) return;
    versionTimer.current = setInterval(async () => {
      const state = useLessonPlanEditor.getState();
      if (!state.isDirty) return;
      try {
        await service.saveLessonPlanVersion({
          planId: state.planId,
          content: state.doc,
          label: t("version.autoLabel"),
        });
      } catch (e) {
        console.error("[LessonPlanEditor] auto-version failed", e);
      }
    }, 30 * 60 * 1000);
    return () => {
      if (versionTimer.current) clearInterval(versionTimer.current);
    };
  }, [planId, t, service]);

  // 离开未保存提示（P3-1）
  useEffect(() => {
    function handleBeforeUnload(e: BeforeUnloadEvent) {
      if (useLessonPlanEditor.getState().isDirty) {
        e.preventDefault();
        e.returnValue = "";
      }
    }
    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => window.removeEventListener("beforeunload", handleBeforeUnload);
  }, []);

  // 添加节点菜单点击外部关闭（P3-2）
  useEffect(() => {
    if (!showAddMenu) return;
    function handleClickOutside(e: MouseEvent) {
      if (addMenuRef.current && !addMenuRef.current.contains(e.target as Node)) {
        setShowAddMenu(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [showAddMenu]);

  const handleManualSave = useCallback(async () => {
    if (!service) return;
    const state = useLessonPlanEditor.getState();
    state.setSaving(true);
    try {
      const res = await service.saveLessonPlanVersion({
        planId: state.planId,
        content: state.doc,
      });
      if (res.success) {
        state.markSaved();
        tracker.track("lesson_plan.save", { planId: state.planId, source: "manual" });
      }
    } catch (e) {
      console.error("[LessonPlanEditor] manual save failed", e);
    } finally {
      state.setSaving(false);
    }
  }, [tracker, service]);

  // 版本回退后刷新内容（修复 P1-1）
  const handleReverted = useCallback(async () => {
    if (!service) return;
    const state = useLessonPlanEditor.getState();
    try {
      const res = await service.getLessonPlanById(state.planId);
      if (res.success && res.data?.plan) {
        state.hydrate(state.planId, res.data.plan.title, res.data.plan.content);
      }
    } catch (e) {
      console.error("[LessonPlanEditor] reload after revert failed", e);
    }
  }, [service]);

  // 发布课案（P0-1 修复）
  const handlePublish = useCallback(async () => {
    if (!service) return;
    setPublishing(true);
    try {
      const res = await service.publishLessonPlan(planId);
      if (res.success) {
        setPlanStatus("published");
        tracker.track("lesson_plan.publish", { planId });
        toast.success(res.message ?? t("action.publishPlanSuccess"));
      } else {
        toast.error(res.message ?? t("error.save"));
      }
    } catch (e) {
      console.error("[LessonPlanEditor] publish failed", e);
      toast.error(t("error.save"));
    } finally {
      setPublishing(false);
    }
  }, [planId, tracker, t, service]);

  // 撤回发布
  const handleUnpublish = useCallback(async () => {
    if (!service) return;
    setPublishing(true);
    try {
      const res = await service.unpublishLessonPlan(planId);
      if (res.success) {
        setPlanStatus("draft");
        tracker.track("lesson_plan.unpublish", { planId });
        toast.success(res.message ?? t("action.unpublishPlanSuccess"));
      } else {
        toast.error(res.message ?? t("error.save"));
      }
    } catch (e) {
      console.error("[LessonPlanEditor] unpublish failed", e);
      toast.error(t("error.save"));
    } finally {
      setPublishing(false);
    }
  }, [planId, tracker, t, service]);

  return (
    <div className="flex flex-col h-full">
      {/* 顶部工具栏 */}
      <div className="flex items-center gap-2 px-4 py-2 border-b border-outline-variant bg-surface">
        <input
          value={editor.title}
          onChange={(e) => editor.setTitle(e.target.value)}
          className="flex-1 bg-transparent font-headline-md text-headline-md focus:outline-none"
        />
        {/* 教材/章节指示器 */}
        {textbookTitle && (
          <div className="flex items-center gap-1 text-xs text-on-surface-variant px-2 py-1 rounded bg-surface-container-high">
            <Book className="w-3 h-3" />
            <span className="max-w-[120px] truncate">{textbookTitle}</span>
            {chapterTitle && (
              <>
                <span className="text-on-surface-variant/50">/</span>
                <FileText className="w-3 h-3" />
                <span className="max-w-[120px] truncate">{chapterTitle}</span>
              </>
            )}
          </div>
        )}
        <span className="text-on-surface-variant text-sm">
          {editor.isSaving
            ? t("status.saving")
            : editor.isDirty
              ? t("status.unsaved")
              : t("status.saved")}
        </span>
        <Button
          variant="outline"
          size="sm"
          onClick={() => setShowVersions(true)}
        >
          <History className="w-4 h-4 mr-1" /> {t("action.versions")}
        </Button>
        <Button size="sm" onClick={handleManualSave} disabled={editor.isSaving}>
          <Save className="w-4 h-4 mr-1" /> {t("action.saveVersion")}
        </Button>
        {/* 发布/撤回发布按钮（P0-1 修复）*/}
        {planStatus === "published" ? (
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button variant="outline" size="sm" disabled={publishing}>
                <Undo2 className="w-4 h-4 mr-1" /> {t("action.unpublishPlan")}
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>{t("action.unpublishPlan")}</AlertDialogTitle>
                <AlertDialogDescription>
                  {t("action.unpublishPlanConfirm")}
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>{t("action.cancel")}</AlertDialogCancel>
                <AlertDialogAction onClick={handleUnpublish}>
                  {t("action.confirm")}
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        ) : (
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button size="sm" disabled={publishing}>
                <Send className="w-4 h-4 mr-1" /> {t("action.publishPlan")}
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>{t("action.publishPlan")}</AlertDialogTitle>
                <AlertDialogDescription>
                  {t("action.publishPlanConfirm")}
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>{t("action.cancel")}</AlertDialogCancel>
                <AlertDialogAction onClick={handlePublish}>
                  {t("action.confirm")}
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        )}
      </div>

      {/* 主区域：画布 + 侧边面板 */}
      <div className="flex-1 flex overflow-hidden">
        {/* 节点画布 */}
        <div className="flex-1 relative">
          <LessonPlanErrorBoundary>
            <NodeEditor />
          </LessonPlanErrorBoundary>
          {/* 添加节点浮动按钮 */}
          <div className="absolute bottom-4 left-4 z-10" ref={addMenuRef}>
            <Button
              variant="default"
              onClick={() => setShowAddMenu(!showAddMenu)}
            >
              <Plus className="w-4 h-4 mr-1" /> {t("action.addNode")}
            </Button>
            {showAddMenu && (
              <div className="absolute bottom-12 left-0 bg-surface border border-outline-variant rounded-lg shadow-lg p-2 grid grid-cols-2 gap-1 w-72 max-h-[60vh] overflow-y-auto">
                {BLOCK_TYPES_TO_ADD.map((blockType) => (
                  <button
                    key={blockType}
                    onClick={() => {
                      editor.addNode(blockType, undefined, t(`blockType.${blockType}`));
                      setShowAddMenu(false);
                    }}
                    className="text-left px-2 py-1 text-sm hover:bg-surface-container-highest rounded"
                  >
                    {t(`blockType.${blockType}`)}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* 侧边内容编辑面板：直接用 selectedNodeId 控制显示（修复 P1-2） */}
        {editor.selectedNodeId && (
          <div className="w-[420px] flex-shrink-0">
            <NodeEditPanel
              textbookId={textbookId}
              chapterId={chapterId}
              classes={classes}
              aiContentGenerator={aiContentGenerator}
            />
          </div>
        )}
      </div>

      <LessonPlanErrorBoundary>
        <VersionHistoryDrawer
          open={showVersions}
          onClose={() => setShowVersions(false)}
          planId={planId}
          onReverted={handleReverted}
        />
      </LessonPlanErrorBoundary>
    </div>
  );
}
