"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
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 { duplicateLessonPlanAction, deleteLessonPlanAction } from "../actions";
import { useLessonPlanContextSafe, useRoleConfig, useLessonPlanTrackerSafe } from "../providers/lesson-plan-provider";
import type { LessonPlanListItem } from "../types";

export function LessonPlanCard({ plan }: { plan: LessonPlanListItem }) {
  const t = useTranslations("lessonPreparation");
  const router = useRouter();
  const roleConfig = useRoleConfig();
  const tracker = useLessonPlanTrackerSafe();

  // 尝试使用注入的数据服务，若未在 Provider 内则 fallback 到直接调用 actions
  const ctx = useLessonPlanContextSafe();
  const service = ctx?.service ?? null;

  async function handleArchive() {
    const res = service
      ? await service.deleteLessonPlan(plan.id)
      : await deleteLessonPlanAction(plan.id);
    if (res.success) {
      tracker.track("lesson_plan.archive", { planId: plan.id });
      toast.success(t("status.archived"));
      router.refresh();
    } else {
      toast.error(res.message ?? t("error.delete"));
    }
  }

  async function handleDuplicate() {
    const res = service
      ? await service.duplicateLessonPlan(plan.id)
      : await duplicateLessonPlanAction(plan.id);
    if (res.success) {
      tracker.track("lesson_plan.duplicate", { planId: plan.id });
      router.refresh();
    }
  }

  return (
    <div className="border border-outline-variant rounded-lg p-4 bg-surface-container-lowest hover:shadow-md transition-shadow">
      <Link
        href={`/teacher/lesson-plans/${plan.id}/edit`}
        className="block"
      >
        <h3 className="font-title-md text-title-md hover:text-primary">
          {plan.title}
        </h3>
      </Link>
      <div className="text-sm text-on-surface-variant mt-1">
        {plan.textbookTitle ?? t("list.noTextbook")} · {plan.chapterTitle ?? t("list.noChapter")}
      </div>
      <div className="text-xs text-on-surface-variant mt-1">
        {plan.templateName ?? t("list.noTemplate")} ·{" "}
        {t(`status.${plan.status}`)}
      </div>
      <div className="text-xs text-on-surface-variant mt-2">
        {t("list.lastSaved")}
        {plan.lastSavedAt
          ? formatDateTime(plan.lastSavedAt)
          : t("list.neverSaved")}
      </div>
      <div className="flex gap-2 mt-3">
        {roleConfig.canDuplicate && (
          <Button variant="outline" size="sm" onClick={handleDuplicate}>
            {t("action.duplicate")}
          </Button>
        )}
        {roleConfig.canArchive && (
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button variant="outline" size="sm">
                {t("action.archive")}
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>{t("confirm.archiveTitle")}</AlertDialogTitle>
                <AlertDialogDescription>
                  {t("confirm.archive")}
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>{t("action.cancel")}</AlertDialogCancel>
                <AlertDialogAction onClick={handleArchive}>
                  {t("action.confirm")}
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        )}
      </div>
    </div>
  );
}
