import type { JSX } from "react";
import Link from "next/link";
import { BookOpen, Copy } from "lucide-react";
import { getTranslations } from "next-intl/server";
import { Button } from "@/shared/components/ui/button";
import { EmptyState } from "@/shared/components/ui/empty-state";
import { requirePermission } from "@/shared/lib/auth-guard";
import { Permissions } from "@/shared/types/permissions";
import { getLessonPlans } from "@/modules/lesson-preparation/data-access";
import { duplicateLessonPlanFormAction } from "@/modules/lesson-preparation/actions";
import { formatDateTime } from "@/shared/lib/utils";

export const dynamic = "force-dynamic";

/**
 * V5-12 R4：校内课案库。
 *
 * 展示本校其他教师分享的已发布课案，支持一键复制为自己的课案。
 * 复用现有 getLessonPlans 数据访问（scope 已限定可见范围），
 * 在页面层过滤掉当前用户自己创建的课案。
 */
export default async function LibraryPage(): Promise<JSX.Element> {
  const t = await getTranslations("lessonPreparation");
  const ctx = await requirePermission(Permissions.LESSON_PLAN_READ);

  const allItems = await getLessonPlans(
    { status: "published" },
    ctx.dataScope,
    ctx.userId,
  );

  // 过滤掉当前用户自己创建的课案，仅展示他人分享的
  const libraryItems = allItems.filter((item) => item.creatorId !== ctx.userId);

  return (
    <div className="p-6 space-y-4">
      <div>
        <h1 className="text-2xl font-bold tracking-tight flex items-center gap-2">
          <BookOpen className="h-6 w-6" aria-hidden="true" />
          {t("library.title")}
        </h1>
        <p className="text-muted-foreground">{t("library.description")}</p>
      </div>

      {libraryItems.length === 0 ? (
        <EmptyState
          icon={BookOpen}
          title={t("library.empty")}
          description={t("library.description")}
          className="border-none shadow-none"
        />
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {libraryItems.map((item) => (
            <article
              key={item.id}
              className="border border-outline-variant rounded-lg p-4 bg-surface flex flex-col gap-2"
            >
              <div className="flex-1">
                <h3 className="font-medium text-base line-clamp-2">
                  <Link
                    href={`/teacher/lesson-plans/${item.id}/edit`}
                    className="hover:text-primary"
                  >
                    {item.title}
                  </Link>
                </h3>
                <div className="flex flex-wrap gap-1.5 mt-1 text-xs text-on-surface-variant">
                  {item.subjectName && (
                    <span className="px-1.5 py-0.5 rounded bg-surface-container-highest">
                      {item.subjectName}
                    </span>
                  )}
                  {item.gradeName && (
                    <span className="px-1.5 py-0.5 rounded bg-surface-container-highest">
                      {item.gradeName}
                    </span>
                  )}
                  {item.textbookTitle && (
                    <span className="px-1.5 py-0.5 rounded bg-surface-container-highest truncate max-w-[120px]">
                      {item.textbookTitle}
                    </span>
                  )}
                </div>
                <p className="text-xs text-on-surface-variant mt-2">
                  {t("library.byCreator", {
                    creator: item.creatorName ?? t("library.noCreator"),
                  })}
                  {" · "}
                  {formatDateTime(item.updatedAt)}
                </p>
              </div>
              <form action={duplicateLessonPlanFormAction}>
                <input type="hidden" name="planId" value={item.id} />
                <Button type="submit" variant="outline" size="sm" className="w-full">
                  <Copy className="h-3.5 w-3.5 mr-1" aria-hidden="true" />
                  {t("library.fork")}
                </Button>
              </form>
            </article>
          ))}
        </div>
      )}
    </div>
  );
}
