import { notFound } from "next/navigation";
import Link from "next/link";
import { eq } from "drizzle-orm";
import { db } from "@/db";
import {
  equipmentCategories,
  equipmentCategoryMerkmale,
  merkmale,
} from "@/db/schema";
import { requirePlatformAdmin } from "@/lib/auth/guards";
import { de } from "@/lib/i18n/de";
import {
  CategoryMerkmaleEditor,
  type CategoryMerkmalRow,
  type MerkmalLite,
} from "./CategoryMerkmaleEditor";

export default async function KategorieDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  await requirePlatformAdmin();
  const { id } = await params;

  const [cat] = await db
    .select()
    .from(equipmentCategories)
    .where(eq(equipmentCategories.id, id));
  if (!cat) notFound();

  const [cmRows, alleMerkmale] = await Promise.all([
    db
      .select({
        merkmalId: equipmentCategoryMerkmale.merkmalId,
        name: merkmale.name,
        einheit: merkmale.einheit,
        reihenfolge: equipmentCategoryMerkmale.reihenfolge,
      })
      .from(equipmentCategoryMerkmale)
      .innerJoin(merkmale, eq(merkmale.id, equipmentCategoryMerkmale.merkmalId))
      .where(eq(equipmentCategoryMerkmale.categoryId, id))
      .orderBy(equipmentCategoryMerkmale.reihenfolge, merkmale.name),
    db
      .select({ id: merkmale.id, name: merkmale.name })
      .from(merkmale)
      .where(eq(merkmale.status, "active"))
      .orderBy(merkmale.name),
  ]);

  const rows: CategoryMerkmalRow[] = cmRows;
  const merkmaleLite: MerkmalLite[] = alleMerkmale;

  return (
    <div className="space-y-8">
      <div>
        <Link
          href="/admin/geraete-kategorien"
          className="text-sm text-navy hover:underline"
        >
          ← {de.admin.navKategorien}
        </Link>
        <h1 className="mt-2 font-display text-2xl text-navy">{cat.name}</h1>
      </div>
      <CategoryMerkmaleEditor
        categoryId={id}
        rows={rows}
        alleMerkmale={merkmaleLite}
      />
    </div>
  );
}
