import { UserRole } from "@prisma/client";
import { Mail, Search, SlidersHorizontal, Users } from "lucide-react";

import { requireRole } from "@/lib/auth-utils";
import { prisma } from "@/lib/prisma";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { AddFamilyDialog } from "./add-family-dialog";
import { DutyManager } from "./duty-manager";
import { EditFamilyDialog } from "./edit-family-dialog";

export const metadata = { title: "Familienverwaltung · Kita-Planer" };

// =====================================================================
// /dashboard/families · Server Component
// ---------------------------------------------------------------------
// Zeigt alle Haushalte und deren Eltern/Kinder für die aktuelle
// kitaId. Tenant-Filter ist garantiert: kitaId aus requireRole-Session.
// =====================================================================

export default async function FamiliesPage() {
  // Guard: Nur Admins dürfen die vollständige Familienliste sehen.
  const session = await requireRole([UserRole.ADMIN]);

  const kitaId = session.user.kitaId!;

  // Alle Haushalte der Kita mit Elternteilen und Kindern laden.
  // kitaId IMMER aus der Session — nie aus URL/Params
  const families = await prisma.family.findMany({
    where: { kitaId },
    select: {
      id: true,
      name: true,
      users: {
        select: {
          id: true,
          firstName: true,
          lastName: true,
          email: true,
          emailVerifiedAt: true,
          dutyAssignments: {
            select: {
              id: true,
              dutyId: true,
              duty: {
                select: {
                  name: true,
                },
              },
            },
          },
        },
        orderBy: [{ lastName: "asc" }, { firstName: "asc" }],
      },
      children: {
        select: { id: true, firstName: true, lastName: true },
        orderBy: [{ lastName: "asc" }, { firstName: "asc" }],
      },
    },
    orderBy: { name: "asc" },
  });

  const allDuties = await prisma.parentDuty.findMany({
    where: { kitaId },
    select: {
      id: true,
      name: true,
      assignments: {
        select: {
          id: true,
        },
      },
    },
    orderBy: { name: "asc" },
  });

  const childCount = families.reduce(
    (acc, family) => acc + family.children.length,
    0,
  );
  const canManageDuties = session.user.role === UserRole.ADMIN;
  const pendingInviteCount = families.reduce(
    (acc, family) =>
      acc + family.users.filter((user) => !user.emailVerifiedAt).length,
    0,
  );

  return (
    <div className="mx-auto max-w-[1280px] px-11 py-9 pb-16 max-[760px]:px-5">
      <header className="mb-7 flex items-end justify-between gap-8 max-[900px]:flex-col max-[900px]:items-start">
        <div>
          <p className="text-[11px] font-semibold uppercase text-[var(--accent-deep)] [letter-spacing:0.18em]">
            VERWALTUNG · FAMILIEN
          </p>
          <h1 className="mt-2 text-[36px] font-normal leading-tight tracking-[-0.025em] text-[var(--ink)]">
            Familien{" "}
            <em className="font-normal italic text-[var(--accent-deep)]">
              organisieren
            </em>
          </h1>
          <p className="mt-2 max-w-2xl text-[15px] leading-6 text-[var(--ink-soft)]">
            Haushalte, Elternteile, Kinder und Ämter an einem ruhigen Ort
            pflegen.
          </p>
        </div>
        <div className="flex shrink-0 flex-wrap gap-2">
          <Button variant="ghost" size="sm">
            <SlidersHorizontal className="h-4 w-4 [stroke-width:1.7]" />
            Ansicht
          </Button>
          <AddFamilyDialog />
        </div>
      </header>

      <div className="mb-5 flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-wrap gap-2">
          <DirectoryMetric label="Familien" value={families.length} />
          <DirectoryMetric label="Kinder" value={childCount} />
          <DirectoryMetric label="Offene Einladungen" value={pendingInviteCount} />
        </div>
        <div className="relative min-w-72 max-[760px]:w-full max-[760px]:min-w-0">
          <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--ink-muted)] [stroke-width:1.7]" />
          <Input placeholder="Familien, Eltern oder Kinder suchen" className="pl-9" />
        </div>
      </div>

      {families.length === 0 ? (
        <EmptyState />
      ) : (
        <Card>
          <CardHeader className="flex-row items-start justify-between gap-4">
            <div>
              <CardTitle>Haushalte</CardTitle>
              <p className="mt-1 text-[13.5px] text-[var(--ink-soft)]">
                {families.length} {families.length === 1 ? "Familie" : "Familien"} ·{" "}
                {childCount} Kinder · {pendingInviteCount} offene Einladungen
              </p>
            </div>
            <Badge variant="secondary" className="tabular-nums">
              {families.length}
            </Badge>
          </CardHeader>
          <CardContent className="px-0 pb-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="pl-6">Familie</TableHead>
                  <TableHead>Elternteile</TableHead>
                  <TableHead>Kinder</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="pr-6 text-right">Aktionen</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {families.map((family) => {
                  const hasPendingInvite = family.users.some(
                    (user) => !user.emailVerifiedAt,
                  );

                  return (
                    <TableRow key={family.id}>
                      <TableCell className="pl-6">
                        <div className="flex items-center gap-3">
                          <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-[var(--accent-soft)] text-[13px] font-semibold uppercase text-[var(--accent-deep)]">
                            {family.name.slice(0, 1)}
                          </div>
                          <div>
                            <div className="font-semibold text-[var(--ink)]">
                              {family.name}
                            </div>
                            <div className="mt-0.5 text-xs text-[var(--ink-muted)]">
                              {family.users.length} Elternteil
                              {family.users.length === 1 ? "" : "e"}
                            </div>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="space-y-2">
                          {family.users.map((parent) => (
                            <div key={parent.id} className="min-w-0">
                              <div className="font-medium text-[var(--ink)]">
                                {parent.firstName} {parent.lastName}
                              </div>
                              <div className="mt-0.5 flex items-center gap-1.5 text-xs text-[var(--ink-muted)]">
                                <Mail className="h-3 w-3 shrink-0 [stroke-width:1.7]" />
                                <span className="break-words [overflow-wrap:anywhere]">
                                  {parent.email}
                                </span>
                              </div>
                            </div>
                          ))}
                        </div>
                      </TableCell>
                      <TableCell>
                        {family.children.length === 0 ? (
                          <span className="text-sm italic text-[var(--ink-faint)]">
                            Noch keine Kinder
                          </span>
                        ) : (
                          <div className="flex flex-wrap gap-1.5">
                            {family.children.map((child) => (
                              <span
                                key={child.id}
                                className="inline-flex items-center rounded-full border border-[var(--hairline)] bg-[var(--surface-2)] px-2.5 py-1 text-xs font-medium text-[var(--ink-soft)]"
                              >
                                {child.firstName} {child.lastName}
                              </span>
                            ))}
                          </div>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge variant={hasPendingInvite ? "warning" : "success"}>
                          {hasPendingInvite ? "Einladung offen" : "Aktiv"}
                        </Badge>
                      </TableCell>
                      <TableCell className="pr-6 text-right">
                        <div className="flex flex-wrap justify-end gap-1">
                          <EditFamilyDialog
                            family={{
                              id: family.id,
                              name: family.name,
                              parents: family.users.map((parent) => ({
                                id: parent.id,
                                firstName: parent.firstName,
                                lastName: parent.lastName,
                                email: parent.email,
                              })),
                              children: family.children,
                            }}
                          />
                          {canManageDuties &&
                            family.users.map((parent) => (
                              <DutyManager
                                key={parent.id}
                                user={{
                                  id: parent.id,
                                  firstName: parent.firstName,
                                  lastName: parent.lastName,
                                }}
                                allDuties={allDuties}
                                userAssignments={parent.dutyAssignments}
                              />
                            ))}
                        </div>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

function EmptyState() {
  return (
    <Card className="border-dashed">
      <div className="flex max-h-[280px] min-h-[260px] flex-col items-center justify-center px-6 py-12 text-center">
        <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--accent-soft)] text-[var(--accent-deep)]">
          <Users className="h-6 w-6 [stroke-width:1.7]" />
        </div>
        <h3 className="mb-1 text-lg font-medium tracking-[-0.02em] text-[var(--ink)]">
          Noch keine Familien
        </h3>
        <p className="mb-5 max-w-sm text-sm leading-6 text-[var(--ink-soft)]">
          Lege die erste Familie an und lade das Elternteil per Link ein, sein
          Passwort zu setzen.
        </p>
        <AddFamilyDialog />
      </div>
    </Card>
  );
}

function DirectoryMetric({ label, value }: { label: string; value: number }) {
  return (
    <span className="inline-flex h-9 items-center gap-2 rounded-full border border-[var(--hairline)] bg-[var(--surface)] px-3 text-[13px] font-semibold text-[var(--ink-soft)]">
      <span className="text-[var(--ink)] tabular-nums">
        {value}
      </span>
      {label}
    </span>
  );
}
