import type { Metadata } from "next";
import { LogOut } from "lucide-react";

import { signOut } from "@/auth";
import { requireKitaSession } from "@/lib/auth-utils";
import { prisma } from "@/lib/prisma";
import { Button } from "@/components/ui/button";
import { SidebarNav } from "@/components/dashboard/sidebar-nav";

export const metadata: Metadata = {
  robots: {
    index: false,
    follow: false,
  },
};

// =====================================================================
// Dashboard-Layout · Linke Sidebar
// ---------------------------------------------------------------------
// Server Component: liest kitaId aus der Session, holt den Kita-Namen
// aus der DB und rendert das App-Shell (Sidebar + main content area).
// Der eigentliche Seiteninhalt kommt via {children} rein.
// =====================================================================

export default async function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await requireKitaSession();

  const kita = await prisma.kita.findUniqueOrThrow({
    where: { id: session.user.kitaId },
    select: { name: true },
  });
  const displayName = session.user.name ?? session.user.email ?? "Kita-Planer";

  return (
    <div className="grid min-h-screen grid-cols-[256px_minmax(0,1fr)] bg-[var(--bg)] max-[760px]:grid-cols-1">
      {/* ── Sidebar ───────────────────────────────────────────────────── */}
      <aside className="sticky top-0 flex h-screen shrink-0 flex-col border-r border-[var(--hairline)] bg-[var(--surface)] max-[760px]:relative max-[760px]:h-auto">
        {/* Logo / Kita-Name */}
        <div className="flex h-[82px] items-center gap-3 border-b border-[var(--hairline-soft)] px-5">
          <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--accent-deep)] text-[13px] font-bold text-white">
            {kita.name.slice(0, 1).toUpperCase()}
          </div>
          <div className="min-w-0">
            <p className="truncate text-sm font-semibold leading-none text-[var(--ink)]">
              {kita.name}
            </p>
            <p className="mt-1 text-xs text-[var(--ink-soft)]">Kita-Planer</p>
          </div>
        </div>

        {/* Navigation */}
        <div className="flex-1 overflow-y-auto py-6">
          <SidebarNav role={session.user.role} />
        </div>

        {/* Footer: User-Info + Abmelden */}
        <div className="border-t border-[var(--hairline-soft)] p-4">
          <div className="mb-3 flex items-center gap-2.5 px-1">
            <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--accent-soft)] text-[11px] font-semibold text-[var(--accent-deep)]">
              {getInitials(displayName)}
            </div>
            <div className="min-w-0">
              <p className="truncate text-xs font-semibold text-[var(--ink)]">
                {displayName}
              </p>
              <p className="truncate text-[11px] font-semibold uppercase text-[var(--ink-muted)]">
                {session.user.role}
              </p>
            </div>
          </div>
          <form
            action={async () => {
              "use server";
              await signOut({ redirectTo: "/" });
            }}
          >
            <Button
              type="submit"
              variant="ghost"
              size="sm"
              className="w-full justify-start"
            >
              <LogOut className="h-4 w-4" />
              Abmelden
            </Button>
          </form>
        </div>
      </aside>

      {/* ── Main Content ──────────────────────────────────────────────── */}
      <main className="min-w-0 overflow-y-auto">
        {children}
      </main>
    </div>
  );
}

function getInitials(value: string) {
  const parts = value.trim().split(/\s+/).filter(Boolean);
  if (parts.length >= 2) {
    return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
  }

  return value.slice(0, 2).toUpperCase();
}
