"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { useLessonPlanContextSafe, useLessonPlanTrackerSafe } from "../providers/lesson-plan-provider";
import { Button } from "@/shared/components/ui/button";
import { FocusTrap } from "@/shared/components/a11y/focus-trap";
import { VersionListSkeleton } from "./lesson-plan-skeleton";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/shared/components/ui/alert-dialog";
import { formatDateTime } from "@/shared/lib/utils";
import { VersionDiffView } from "./version-diff-view";
import type { LessonPlanDocument, LessonPlanVersion } from "../types";

interface Props {
  open: boolean;
  onClose: () => void;
  planId: string;
  onReverted: () => void;
  /** V5-16：当前文档（用于版本对比） */
  currentDoc?: LessonPlanDocument;
}

export function VersionHistoryDrawer({
  open,
  onClose,
  planId,
  onReverted,
  currentDoc,
}: Props) {
  const t = useTranslations("lessonPreparation");
  const ctx = useLessonPlanContextSafe();
  const service = ctx?.service ?? null;
  const tracker = useLessonPlanTrackerSafe();
  const [versions, setVersions] = useState<LessonPlanVersion[]>([]);
  const [loading, setLoading] = useState(false);
  /** V5-16：当前正在对比的版本（null 表示显示列表） */
  const [comparingVersion, setComparingVersion] = useState<LessonPlanVersion | null>(null);

  // P1-1 修复：ESC 键关闭抽屉（open 时才监听）
  useEffect(() => {
    if (!open) return;
    function handleEsc(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    document.addEventListener("keydown", handleEsc);
    return () => document.removeEventListener("keydown", handleEsc);
  }, [open, onClose]);

  useEffect(() => {
    if (!open || !service) return;
    let cancelled = false;
    // V4 P2-3 修复：使用 async IIFE + ignore flag 替代 queueMicrotask
    (async () => {
      setLoading(true);
      try {
        const res = await service.getLessonPlanVersions(planId);
        if (cancelled) return;
        if (res.success && res.data) setVersions(res.data.versions);
      } catch (e) {
        if (cancelled) return;
        console.error("[VersionHistoryDrawer] load versions failed", e);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [open, planId, service]);

  async function handleRevert(versionNo: number) {
    if (!service) return;
    try {
      const res = await service.revertLessonPlanVersion({ planId, versionNo });
      if (res.success) {
        tracker.track("lesson_plan.revert", { planId, versionNo });
        toast.success(t("version.revertSuccess", { versionNo }));
        onReverted();
        onClose();
      } else {
        toast.error(res.message ?? t("error.revert"));
      }
    } catch (e) {
      console.error("[VersionHistoryDrawer] revert failed", e);
      toast.error(t("error.revert"));
    }
  }

  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 flex">
      <div className="flex-1 bg-black/30" onClick={onClose} />
      <div className="w-96 bg-surface border-l border-outline-variant overflow-y-auto p-4">
        <FocusTrap className="contents">
        {/* V5-16：版本对比视图（当 comparingVersion 存在时显示） */}
        {comparingVersion && currentDoc ? (
          <div>
            <div className="flex items-center justify-between mb-3">
              <h3 className="font-headline-md text-headline-md">
                {t("diff.comparing", { version: comparingVersion.versionNo })}
              </h3>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setComparingVersion(null)}
              >
                {t("diff.back")}
              </Button>
            </div>
            <VersionDiffView
              oldDoc={comparingVersion.content}
              newDoc={currentDoc}
              oldVersionNo={comparingVersion.versionNo}
            />
          </div>
        ) : (
          <>
            <h3 className="font-headline-md text-headline-md mb-4">{t("version.title")}</h3>
            {loading ? (
              <VersionListSkeleton />
            ) : versions.length === 0 ? (
              <p className="text-on-surface-variant">{t("version.empty")}</p>
            ) : (
              <div className="flex flex-col gap-2">
                {versions.map((v) => (
                  <div
                    key={v.id}
                    className="border border-outline-variant rounded-lg p-3"
                  >
                    <div className="flex justify-between items-center">
                      <span className="font-title-md">v{v.versionNo}</span>
                      {v.isAuto && (
                        <span className="text-xs bg-surface-container-highest px-2 py-0.5 rounded">
                          {t("version.auto")}
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-on-surface-variant">
                      {v.label ?? t("version.manual")}
                    </p>
                    <p className="text-xs text-on-surface-variant mt-1">
                      {formatDateTime(v.createdAt)}
                    </p>
                    <div className="flex gap-2 mt-2">
                      {/* V5-16 T2：对比当前按钮 */}
                      {currentDoc && (
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setComparingVersion(v)}
                        >
                          {t("diff.compareWithCurrent")}
                        </Button>
                      )}
                      <AlertDialog>
                        <AlertDialogTrigger asChild>
                          <Button variant="outline" size="sm">
                            {t("version.revert")}
                          </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader>
                            <AlertDialogTitle>{t("version.revertTitle")}</AlertDialogTitle>
                            <AlertDialogDescription>
                              {t("version.revertConfirm", { versionNo: v.versionNo })}
                            </AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>{t("action.cancel")}</AlertDialogCancel>
                            <AlertDialogAction onClick={() => handleRevert(v.versionNo)}>
                              {t("action.confirm")}
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </>
        )}
        </FocusTrap>
      </div>
    </div>
  );
}
