"use client";

import { useCallback, useEffect, useMemo, 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, RotateCw, WifiOff, Printer, Undo, Redo, CalendarClock, ClipboardCheck, Sparkles, Layers } from "lucide-react";
import { toast } from "sonner";
import { PrintView } from "./print-view";
import { ScheduleDialog } from "./schedule-dialog";
import { ConsistencyCheckDialog } from "./consistency-check-dialog";
import { AiFeedbackDialog } from "./ai-feedback-dialog";
import { AiDifferentiationDialog } from "./ai-differentiation-dialog";
import type { LessonPlan, LessonPlanDocument } from "../types";

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 [showPrint, setShowPrint] = useState(false); // V5-4：打印视图
  const [showSchedule, setShowSchedule] = useState(false); // V5-7：安排课时对话框
  const [showConsistency, setShowConsistency] = useState(false); // V5-19：一致性校验对话框
  const [showAiFeedback, setShowAiFeedback] = useState(false); // V5-17：AI 反馈对话框
  const [showAiDifferentiation, setShowAiDifferentiation] = useState(false); // V5-21：AI 差异化对话框
  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
  // V5-1 修复：保存失败显示 toast + 设置 saveError；断网时不触发保存
  useEffect(() => {
    if (!editor.isDirty) return;
    if (!service) return;
    if (!editor.isOnline) return; // V5-1：断网期间不触发保存请求
    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) {
          // V5-1：从失败恢复到成功时提示
          if (state.saveError) toast.success(t("status.recovered"));
          state.markSaved();
        } else {
          state.setSaveError(true);
          toast.error(t("status.saveFailed"), { description: t("status.saveFailedHint") });
        }
      } catch (e) {
        console.error("[LessonPlanEditor] auto-save failed", e);
        state.setSaveError(true);
        toast.error(t("status.saveFailed"), { description: t("status.saveFailedHint") });
      } finally {
        state.setSaving(false);
      }
    }, 3000);
    return () => {
      if (autoSaveTimer.current) clearTimeout(autoSaveTimer.current);
    };
  }, [editor.isDirty, editor.doc, planId, service, editor.isOnline, t]);

  // V5-1：监听网络在线/离线状态
  useEffect(() => {
    function handleOnline() {
      useLessonPlanEditor.getState().setOnline(true);
      toast.success(t("status.backOnline"));
    }
    function handleOffline() {
      useLessonPlanEditor.getState().setOnline(false);
      toast.error(t("status.offline"), { description: t("status.offlineHint") });
    }
    window.addEventListener("online", handleOnline);
    window.addEventListener("offline", handleOffline);
    return () => {
      window.removeEventListener("online", handleOnline);
      window.removeEventListener("offline", handleOffline);
    };
  }, [t]);

  // V5-1：手动重试保存（saveError 时显示按钮）
  const handleRetrySave = useCallback(async () => {
    if (!service) return;
    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) {
        toast.success(t("status.recovered"));
        state.markSaved();
      } else {
        toast.error(t("status.saveFailed"));
      }
    } catch (e) {
      console.error("[LessonPlanEditor] retry save failed", e);
      toast.error(t("status.saveFailed"));
    } finally {
      state.setSaving(false);
    }
  }, [service, t]);

  // V5-2：撤销/重做快捷键（Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z 或 Cmd/Ctrl+Y）
  useEffect(() => {
    function handleKeyDown(e: KeyboardEvent) {
      const isMod = e.metaKey || e.ctrlKey;
      if (!isMod) return;
      const key = e.key.toLowerCase();
      if (key === "z" && !e.shiftKey) {
        e.preventDefault();
        const state = useLessonPlanEditor.getState();
        if (state.canUndo()) state.undo();
      } else if ((key === "z" && e.shiftKey) || key === "y") {
        e.preventDefault();
        const state = useLessonPlanEditor.getState();
        if (state.canRedo()) state.redo();
      }
    }
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, []);

  // V5-2：撤销/重做按钮处理（追踪 canUndo/canRedo 以驱动 disabled 状态）
  const canUndo = editor.canUndo();
  const canRedo = editor.canRedo();
  const handleUndo = useCallback(() => useLessonPlanEditor.getState().undo(), []);
  const handleRedo = useCallback(() => useLessonPlanEditor.getState().redo(), []);

  // V5-4：构造打印用的 LessonPlan 对象（编辑器仅持有 planId/title/doc，其余字段填默认值）
  const printablePlan: LessonPlan = useMemo(() => {
    const doc: LessonPlanDocument = editor.doc;
    return {
      id: planId,
      title: editor.title,
      textbookId: textbookId ?? null,
      chapterId: chapterId ?? null,
      coursePlanItemId: null,
      subjectId: null,
      gradeId: null,
      templateId: null,
      templateName: null,
      content: doc,
      status: planStatus,
      creatorId: "",
      lastSavedAt: editor.lastSavedAt ? new Date(editor.lastSavedAt).toISOString() : null,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
  }, [planId, editor.title, editor.doc, editor.lastSavedAt, textbookId, chapterId, planStatus]);

  // 定时自动版本（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>
        {/* V5-1：保存失败/离线提示与重试按钮 */}
        {editor.saveError && (
          <Button
            variant="outline"
            size="sm"
            onClick={handleRetrySave}
            disabled={editor.isSaving}
            className="text-error border-error"
          >
            <RotateCw className="w-3 h-3 mr-1" />
            {t("status.retrySave")}
          </Button>
        )}
        {!editor.isOnline && (
          <span className="text-xs text-error inline-flex items-center gap-1">
            <WifiOff className="w-3 h-3" />
            {t("status.offlineBadge")}
          </span>
        )}
        <Button
          variant="outline"
          size="sm"
          onClick={() => setShowVersions(true)}
        >
          <History className="w-4 h-4 mr-1" /> {t("action.versions")}
        </Button>
        {/* V5-2：撤销/重做按钮 */}
        <Button
          variant="outline"
          size="sm"
          onClick={handleUndo}
          disabled={!canUndo}
          aria-label={t("action.undo")}
          title={t("action.undoShortcut")}
        >
          <Undo className="w-4 h-4" />
        </Button>
        <Button
          variant="outline"
          size="sm"
          onClick={handleRedo}
          disabled={!canRedo}
          aria-label={t("action.redo")}
          title={t("action.redoShortcut")}
        >
          <Redo className="w-4 h-4" />
        </Button>
        <Button size="sm" onClick={handleManualSave} disabled={editor.isSaving}>
          <Save className="w-4 h-4 mr-1" /> {t("action.saveVersion")}
        </Button>
        {/* V5-4：导出/打印按钮 */}
        <Button
          variant="outline"
          size="sm"
          onClick={() => setShowPrint(true)}
          aria-label={t("export.title")}
        >
          <Printer className="w-4 h-4 mr-1" /> {t("export.button")}
        </Button>
        {/* V5-7：安排课时按钮 */}
        {classes && classes.length > 0 && (
          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowSchedule(true)}
            aria-label={t("action.scheduleLesson")}
          >
            <CalendarClock className="w-4 h-4 mr-1" /> {t("action.scheduleLesson")}
          </Button>
        )}
        {/* V5-19 T3：一致性校验按钮 */}
        <Button
          variant="outline"
          size="sm"
          onClick={() => setShowConsistency(true)}
          aria-label={t("editor.consistencyOpen")}
        >
          <ClipboardCheck className="w-4 h-4 mr-1" /> {t("editor.consistencyOpen")}
        </Button>
        {/* V5-17 A1/A2：AI 反馈按钮 */}
        <Button
          variant="outline"
          size="sm"
          onClick={() => setShowAiFeedback(true)}
          aria-label={t("feedback.open")}
        >
          <Sparkles className="w-4 h-4 mr-1" /> {t("feedback.open")}
        </Button>
        {/* V5-21 A3/A4/A5：AI 差异化与课标核对按钮 */}
        <Button
          variant="outline"
          size="sm"
          onClick={() => setShowAiDifferentiation(true)}
          aria-label={t("aiDifferentiation.open")}
        >
          <Layers className="w-4 h-4 mr-1" /> {t("aiDifferentiation.open")}
        </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
              planId={planId}
              textbookId={textbookId}
              chapterId={chapterId}
              classes={classes}
              aiContentGenerator={aiContentGenerator}
            />
          </div>
        )}
      </div>

      <LessonPlanErrorBoundary>
        <VersionHistoryDrawer
          open={showVersions}
          onClose={() => setShowVersions(false)}
          planId={planId}
          onReverted={handleReverted}
          currentDoc={editor.doc}
        />
      </LessonPlanErrorBoundary>

      {/* V5-4：导出/打印视图 */}
      {showPrint && (
        <LessonPlanErrorBoundary>
          <PrintView
            plan={printablePlan}
            textbookTitle={textbookTitle}
            chapterTitle={chapterTitle}
            onClose={() => setShowPrint(false)}
          />
        </LessonPlanErrorBoundary>
      )}

      {/* V5-7：安排课时对话框 */}
      {showSchedule && classes && classes.length > 0 && (
        <LessonPlanErrorBoundary>
          <ScheduleDialog
            planId={planId}
            classes={classes}
            onClose={() => setShowSchedule(false)}
          />
        </LessonPlanErrorBoundary>
      )}

      {/* V5-19 T3：一致性校验对话框 */}
      {showConsistency && (
        <LessonPlanErrorBoundary>
          <ConsistencyCheckDialog
            doc={editor.doc}
            onClose={() => setShowConsistency(false)}
          />
        </LessonPlanErrorBoundary>
      )}

      {/* V5-17 A1/A2：AI 反馈对话框 */}
      {showAiFeedback && (
        <LessonPlanErrorBoundary>
          <AiFeedbackDialog
            doc={editor.doc}
            onClose={() => setShowAiFeedback(false)}
          />
        </LessonPlanErrorBoundary>
      )}

      {/* V5-21 A3/A4/A5：AI 差异化与课标核对对话框 */}
      {showAiDifferentiation && (
        <LessonPlanErrorBoundary>
          <AiDifferentiationDialog
            doc={editor.doc}
            textbookId={textbookId}
            onClose={() => setShowAiDifferentiation(false)}
          />
        </LessonPlanErrorBoundary>
      )}
    </div>
  );
}
