import { notFound } from "next/navigation";
import Link from "next/link";
import { eq } from "drizzle-orm";
import { db } from "@/db";
import { brigades, users } from "@/db/schema";
import { requirePlatformAdmin } from "@/lib/auth/guards";
import { de } from "@/lib/i18n/de";
import { DataTable } from "@/components/admin/DataTable";
import { UserResetButton } from "./UserResetButton";

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

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

  const benutzer = await db
    .select()
    .from(users)
    .where(eq(users.brigadeId, id))
    .orderBy(users.name);

  return (
    <div className="space-y-6">
      <div>
        <Link href="/admin/wehren" className="text-sm text-navy hover:underline">
          ← {de.admin.navWehren}
        </Link>
        <h1 className="mt-2 font-display text-2xl text-navy">{brigade.name}</h1>
        <p className="text-sm text-anthrazit/70">
          {[brigade.strasse, `${brigade.plz ?? ""} ${brigade.ort ?? ""}`.trim()]
            .filter(Boolean)
            .join(", ")}
        </p>
        {brigade.lat == null || brigade.lng == null ? (
          <p className="mt-1 text-sm text-wartung">{de.admin.geocodeFehler}</p>
        ) : (
          <p className="mt-1 text-sm text-bereit">{de.admin.geocodeOk}</p>
        )}
      </div>

      <section className="space-y-3">
        <h2 className="font-display text-lg text-navy">Benutzer</h2>
        <DataTable
          rows={benutzer}
          getRowKey={(u) => u.id}
          columns={[
            {
              key: "name",
              header: de.admin.name,
              render: (u) => (
                <span className="font-medium text-anthrazit">{u.name}</span>
              ),
            },
            { key: "email", header: de.auth.email, render: (u) => u.email },
            { key: "rolle", header: "Rolle", render: (u) => u.rolle },
            {
              key: "reset",
              header: "",
              className: "text-right",
              render: (u) => (
                <UserResetButton userId={u.id} authTyp={u.authTyp} />
              ),
            },
          ]}
        />
      </section>
    </div>
  );
}
