import { UserRole } from "@prisma/client";

import { requireRole } from "@/lib/auth-utils";
import { prisma } from "@/lib/prisma";
import { Badge } from "@/components/ui/badge";
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;

  return (
    <div className="px-8 py-8">
      {/* Header */}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">
            Familienverwaltung
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            {families.length === 0
              ? "Noch keine Familien angelegt."
              : `${families.length} ${families.length === 1 ? "Familie" : "Familien"} · ${childCount} Kinder`}
          </p>
        </div>
        <AddFamilyDialog />
      </div>

      {families.length === 0 ? (
        <EmptyState />
      ) : (
        <div className="rounded-lg border bg-background">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Familie</TableHead>
                <TableHead>Elternteile</TableHead>
                <TableHead>Kinder</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="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="font-medium">
                      {family.name}
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1.5">
                        {family.users.map((parent) => (
                          <div key={parent.id}>
                            <div className="font-medium">
                              {parent.firstName} {parent.lastName}
                            </div>
                            <div className="text-xs text-muted-foreground">
                              {parent.email}
                            </div>
                          </div>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      {family.children.length === 0 ? (
                        <span className="text-sm text-muted-foreground">—</span>
                      ) : (
                        <div className="flex flex-wrap gap-1">
                          {family.children.map((child) => (
                            <span
                              key={child.id}
                              className="inline-flex items-center rounded-md bg-muted px-2 py-0.5 text-xs font-medium"
                            >
                              {child.firstName} {child.lastName}
                            </span>
                          ))}
                        </div>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant={hasPendingInvite ? "warning" : "success"}>
                        {hasPendingInvite ? "Einladung offen" : "Aktiv"}
                      </Badge>
                    </TableCell>
                    <TableCell className="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>
        </div>
      )}
    </div>
  );
}

function EmptyState() {
  return (
    <div className="flex flex-col items-center justify-center rounded-lg border border-dashed bg-background px-6 py-16 text-center">
      <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">
        <svg
          className="h-6 w-6 text-muted-foreground"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={1.5}
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
          />
        </svg>
      </div>
      <h3 className="mb-1 font-semibold">Noch keine Familien</h3>
      <p className="mb-4 max-w-sm text-sm text-muted-foreground">
        Lege die erste Familie an und lade das Elternteil per Link ein, sein
        Passwort zu setzen.
      </p>
      <AddFamilyDialog />
    </div>
  );
}
