import { Baby, Contact, Mail, Phone, ShieldCheck, UsersRound } from "lucide-react";

import { requireKitaSession } from "@/lib/auth-utils";
import { prisma } from "@/lib/prisma";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";

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

type DirectoryFamilyDto = {
  id: string;
  name: string;
  children: {
    id: string;
    firstName: string;
    lastName: string;
  }[];
  parents: {
    id: string;
    firstName: string;
    lastName: string;
    hasDirectoryOptIn: boolean;
    email?: string;
    phone?: string;
    duties: {
      id: string;
      name: string;
    }[];
  }[];
};

export default async function AdressbuchPage() {
  const session = await requireKitaSession();

  const familyRows = await prisma.family.findMany({
    where: {
      kitaId: session.user.kitaId,
      users: {
        some: {
          directoryOptInAt: { not: null },
        },
      },
    },
    select: {
      id: true,
      name: true,
      children: {
        select: {
          id: true,
          firstName: true,
          lastName: true,
        },
        orderBy: [{ lastName: "asc" }, { firstName: "asc" }],
      },
      users: {
        select: {
          id: true,
          firstName: true,
          lastName: true,
          directoryOptInAt: true,
          dutyAssignments: {
            select: {
              id: true,
              duty: {
                select: {
                  name: true,
                },
              },
            },
          },
        },
        orderBy: [{ lastName: "asc" }, { firstName: "asc" }],
      },
    },
    orderBy: { name: "asc" },
  });

  const visibleContactRows = await prisma.user.findMany({
    where: {
      kitaId: session.user.kitaId,
      directoryOptInAt: { not: null },
      familyId: { in: familyRows.map((family) => family.id) },
    },
    select: {
      id: true,
      email: true,
      phone: true,
    },
  });
  const visibleContactsByUserId = new Map(
    visibleContactRows.map((user) => [user.id, user]),
  );

  const families: DirectoryFamilyDto[] = familyRows.map((family) => ({
    id: family.id,
    name: family.name,
    children: family.children,
    parents: family.users.map((user) => {
      const hasDirectoryOptIn = !!user.directoryOptInAt;
      const contact = visibleContactsByUserId.get(user.id);
      return {
        id: user.id,
        firstName: user.firstName,
        lastName: user.lastName,
        hasDirectoryOptIn,
        email: contact?.email,
        phone: contact?.phone ?? undefined,
        duties: user.dutyAssignments.map((assignment) => ({
          id: assignment.id,
          name: assignment.duty.name,
        })),
      };
    }),
  }));

  return (
    <div className="flex h-full flex-col gap-6 p-6">
      <div className="flex flex-col gap-1">
        <h1 className="text-2xl font-bold tracking-tight">Adressbuch</h1>
        <p className="max-w-2xl text-sm text-muted-foreground">
          Haushalte und Kontaktdaten, die explizit für das interne
          Kita-Adressbuch freigegeben wurden.
        </p>
      </div>

      {families.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-lg border border-dashed bg-background p-10 text-center">
          <Contact className="mb-4 h-10 w-10 text-muted-foreground" />
          <h3 className="text-lg font-semibold">Keine freigegebenen Kontakte</h3>
          <p className="mt-2 max-w-sm text-sm text-muted-foreground">
            Sobald mindestens ein Elternteil eines Haushalts zustimmt,
            erscheint die Familie hier.
          </p>
        </div>
      ) : (
        <div className="grid gap-4 lg:grid-cols-2">
          {families.map((family) => (
            <Card key={family.id} className="overflow-hidden">
              <CardHeader className="border-b bg-muted/30 pb-4">
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <CardTitle className="flex items-center gap-2 text-lg">
                      <UsersRound className="h-4 w-4 text-primary" />
                      {family.name}
                    </CardTitle>
                    <CardDescription className="mt-1">
                      {family.parents.filter((user) => user.hasDirectoryOptIn).length}{" "}
                      von {family.parents.length} Elternteilen sichtbar
                    </CardDescription>
                  </div>
                  <Badge variant="success">Freigegeben</Badge>
                </div>
              </CardHeader>

              <CardContent className="grid gap-5 pt-5">
                <section className="space-y-2">
                  <div className="flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
                    <Baby className="h-3.5 w-3.5" />
                    Kinder
                  </div>
                  {family.children.length === 0 ? (
                    <p className="text-sm text-muted-foreground">
                      Keine Kinder hinterlegt.
                    </p>
                  ) : (
                    <div className="flex flex-wrap gap-1.5">
                      {family.children.map((child) => (
                        <Badge key={child.id} variant="secondary">
                          {child.firstName} {child.lastName}
                        </Badge>
                      ))}
                    </div>
                  )}
                </section>

                <section className="grid gap-3">
                  <div className="flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
                    <ShieldCheck className="h-3.5 w-3.5" />
                    Kontakte
                  </div>
                  <div className="grid gap-3">
                    {family.parents.map((user) => {
                      return (
                        <div
                          key={user.id}
                          className="rounded-md border bg-background p-3"
                        >
                          <div className="flex items-start justify-between gap-3">
                            <div>
                              <p className="font-medium">
                                {user.firstName} {user.lastName}
                              </p>
                              {!user.hasDirectoryOptIn && (
                                <p className="mt-0.5 text-xs text-muted-foreground">
                                  Kontakt nicht freigegeben.
                                </p>
                              )}
                            </div>
                            {user.hasDirectoryOptIn ? (
                              <Badge variant="outline">Opt-in</Badge>
                            ) : null}
                          </div>

                          {user.hasDirectoryOptIn && (
                            <div className="mt-3 grid gap-2 text-sm text-muted-foreground">
                              {user.email && (
                                <a
                                  href={`mailto:${user.email}`}
                                  className="flex min-w-0 items-center gap-2 hover:text-primary"
                                >
                                  <Mail className="h-4 w-4 shrink-0" />
                                  <span className="truncate">{user.email}</span>
                                </a>
                              )}
                              {user.phone && (
                                <a
                                  href={`tel:${user.phone}`}
                                  className="flex items-center gap-2 hover:text-primary"
                                >
                                  <Phone className="h-4 w-4 shrink-0" />
                                  {user.phone}
                                </a>
                              )}
                            </div>
                          )}

                          {user.duties.length > 0 && (
                            <div className="mt-3 flex flex-wrap gap-1.5 border-t pt-3">
                              {user.duties.map((duty) => (
                                <Badge
                                  key={duty.id}
                                  variant="outline"
                                  className="bg-primary/5 text-primary"
                                >
                                  {duty.name}
                                </Badge>
                              ))}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </section>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
