"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import {
  getLessonPlanVersionsAction,
  revertLessonPlanVersionAction,
} from "../actions";
import { useLessonPlanTrackerSafe } from "../providers/lesson-plan-provider";
import { Button } from "@/shared/components/ui/button";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/shared/components/ui/alert-dialog";
import { formatDateTime } from "@/shared/lib/utils";
import type { LessonPlanVersion } from "../types";

interface Props {
  open: boolean;
  onClose: () => void;
  planId: string;
  onReverted: () => void;
}

export function VersionHistoryDrawer({
  open,
  onClose,
  planId,
  onReverted,
}: Props) {
  const t = useTranslations("lessonPreparation");
  const tracker = useLessonPlanTrackerSafe();
  const [versions, setVersions] = useState<LessonPlanVersion[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    // 用微任务延迟避免同步 setState 触发级联渲染
    queueMicrotask(() => {
      if (cancelled) return;
      setLoading(true);
      getLessonPlanVersionsAction(planId).then((res) => {
        if (cancelled) return;
        if (res.success && res.data) setVersions(res.data.versions);
        setLoading(false);
      });
    });
    return () => {
      cancelled = true;
    };
  }, [open, planId]);

  async function handleRevert(versionNo: number) {
    const res = await revertLessonPlanVersionAction({ 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"));
    }
  }

  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">
        <h3 className="font-headline-md text-headline-md mb-4">{t("version.title")}</h3>
        {loading ? (
          <p>{t("version.loading")}</p>
        ) : 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>
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button variant="outline" size="sm" className="mt-2">
                      {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>
    </div>
  );
}
