import { format } from "date-fns";
import { de } from "date-fns/locale";
import {
  AtSign,
  Baby,
  CalendarHeart,
  Home,
  Mail,
  Phone,
  Shield,
  Trash2,
  UserCircle,
} from "lucide-react";

import { requireKitaSession } from "@/lib/auth-utils";
import { prisma } from "@/lib/prisma";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { DefItem, DefList, EmptyDefValue } from "@/components/ui/def-list";
import { RoleBadge } from "@/components/ui/role-badge";
import { DeleteAccountDialog } from "./_components/delete-account-dialog";
import { MyChildrenManager } from "./_components/my-children-manager";
import { CreateFamilyDialog } from "./_components/create-family-dialog";
import { ContactForm } from "./_components/contact-form";

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

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

  const [kita, user] = await Promise.all([
    prisma.kita.findUniqueOrThrow({
      where: { id: session.user.kitaId },
      select: { name: true },
    }),
    prisma.user.findUniqueOrThrow({
      where: { id: session.user.id },
      select: {
        id: true,
        email: true,
        firstName: true,
        lastName: true,
        role: true,
        familyId: true,
        phone: true,
        street: true,
        postalCode: true,
        city: true,
        createdAt: true,
        family: {
          select: {
            name: true,
            children: {
              select: {
                id: true,
                firstName: true,
                lastName: true,
                dateOfBirth: true,
              },
              orderBy: [{ lastName: "asc" }, { firstName: "asc" }],
            },
          },
        },
        dutyAssignments: {
          select: {
            id: true,
            duty: {
              select: {
                name: true,
              },
            },
          },
        },
      },
    }),
  ]);

  const fullName = `${user.firstName} ${user.lastName}`.trim();

  return (
    <div className="mx-auto max-w-[1280px] px-11 py-9 pb-16 max-[760px]:px-5">
      <header className="mb-9">
        <p className="text-[11px] font-semibold uppercase text-[var(--accent-deep)] [letter-spacing:0.18em]">
          PROFIL · {kita.name}
        </p>
        <h1 className="mt-2 text-[36px] font-normal leading-tight tracking-[-0.025em] text-[var(--ink)]">
          Mein{" "}
          <em className="font-normal italic text-[var(--accent-deep)]">
            Profil
          </em>
        </h1>
        <p className="mt-3 max-w-2xl text-[15px] leading-6 text-[var(--ink-soft)]">
          Deine persönlichen Daten, verknüpfte Kinder und DSGVO-Einstellungen.
        </p>
      </header>

      <div className="grid items-start gap-5 lg:grid-cols-2">
        <Card className="self-stretch">
          <CardHeader className="pb-5">
            <div className="flex items-start gap-3">
              <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--accent-soft)] text-[var(--accent-deep)]">
                <UserCircle className="h-4 w-4 [stroke-width:1.7]" />
              </div>
              <div>
                <CardTitle>Persönliche Daten</CardTitle>
                <CardDescription className="mt-2">
                  Read-only Stammdaten deines Accounts.
                </CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <DefList>
              <DefItem icon={UserCircle} label="Name" value={fullName} />
              <DefItem icon={Mail} label="E-Mail" value={user.email} />
              <DefItem
                icon={Phone}
                label="Telefon"
                value={user.phone ? user.phone : <EmptyDefValue />}
              />
              <DefItem icon={Shield} label="Rolle" value={<RoleBadge role={user.role} />} />
              <DefItem
                icon={Home}
                label="Haushalt"
                value={
                  user.family ? (
                    user.family.name
                  ) : (
                    <div className="grid gap-3 rounded-lg border border-dashed border-[var(--hairline)] bg-[var(--surface-2)] p-3">
                      <p className="text-sm font-normal leading-5 text-[var(--ink-soft)]">
                        Dein Account ist noch keinem Haushalt zugeordnet.
                      </p>
                      <CreateFamilyDialog
                        defaultFamilyName={`Familie ${user.lastName}`}
                      />
                    </div>
                  )
                }
              />
              <DefItem
                icon={CalendarHeart}
                label="Mitglied seit"
                value={format(user.createdAt, "PPP", { locale: de })}
              />
            </DefList>
          </CardContent>
        </Card>

        <div className="grid gap-4">
          <Card>
            <CardHeader className="pb-5">
              <div className="flex items-start gap-3">
                <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--accent-soft)] text-[var(--accent-deep)]">
                  <AtSign className="h-4 w-4 [stroke-width:1.7]" />
                </div>
                <div>
                  <CardTitle>Kontaktdaten</CardTitle>
                  <CardDescription className="mt-2">
                    Für Notdienst, Adressbuch und Abstimmung in der Kita.
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <ContactForm
                contact={{
                  phone: user.phone,
                  street: user.street,
                  postalCode: user.postalCode,
                  city: user.city,
                }}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-5">
              <div className="flex items-start gap-3">
                <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--accent-soft)] text-[var(--accent-deep)]">
                  <Baby className="h-4 w-4 [stroke-width:1.7]" />
                </div>
                <div>
                  <CardTitle>Meine Kinder</CardTitle>
                  <CardDescription className="mt-2">
                    Kinder deines Haushalts verwalten.
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <MyChildrenManager
                items={(user.family?.children ?? []).map((child) => ({
                  id: child.id,
                  firstName: child.firstName,
                  lastName: child.lastName,
                  dateOfBirth: child.dateOfBirth
                    ? child.dateOfBirth.toISOString().slice(0, 10)
                    : null,
                }))}
                canManage={!!user.familyId}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-5">
              <div className="flex items-start gap-3">
                <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--accent-soft)] text-[var(--accent-deep)]">
                  <Shield className="h-4 w-4 [stroke-width:1.7]" />
                </div>
                <div>
                  <CardTitle>Meine Ämter & Dienste</CardTitle>
                  <CardDescription className="mt-2">
                    Feste Aufgaben und laufende Zuständigkeiten.
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {user.dutyAssignments.length === 0 ? (
                <div className="flex min-h-32 flex-col items-center justify-center rounded-[14px] border border-dashed border-[var(--hairline)] bg-[var(--surface-2)] p-5 text-center">
                  <div className="flex h-9 w-9 items-center justify-center rounded-full bg-[var(--accent-soft)] text-[var(--accent-deep)]">
                    <Shield className="h-4 w-4 [stroke-width:1.7]" />
                  </div>
                  <p className="mt-3 text-sm font-medium text-[var(--ink)]">
                    Keine festen Ämter übernommen
                  </p>
                  <p className="mt-1 text-xs text-[var(--ink-soft)]">
                    Dienste und Rollen erscheinen hier, sobald sie zugewiesen
                    sind.
                  </p>
                </div>
              ) : (
                <div className="grid gap-2">
                  {user.dutyAssignments.map((assignment) => (
                    <div
                      key={assignment.id}
                      className="flex items-center justify-between gap-3 rounded-lg bg-[var(--surface-2)] p-[10px_12px]"
                    >
                      <div>
                        <p className="text-sm font-semibold text-[var(--ink)]">
                          {assignment.duty.name}
                        </p>
                        <p className="text-xs text-[var(--ink-soft)]">
                          laufender Dienst
                        </p>
                      </div>
                      <span className="rounded-full border border-[var(--accent-mid)] bg-[var(--accent-soft)] px-2.5 py-1 text-[10.5px] font-semibold uppercase text-[var(--accent-deep)] [letter-spacing:0.1em]">
                        Aktiv
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      <Card className="mt-5 bg-[var(--surface-2)]">
        <CardContent className="flex items-center justify-between gap-6 pt-[22px] max-[760px]:flex-col max-[760px]:items-start">
          <div className="max-w-2xl">
            <div className="flex items-center gap-2 text-[var(--danger)]">
              <Trash2 className="h-4 w-4 [stroke-width:1.7]" />
              <h2 className="text-lg font-medium tracking-[-0.02em]">
                Danger Zone
              </h2>
            </div>
            <p className="mt-2 text-[13.5px] leading-5 text-[var(--ink-soft)]">
              Hier kannst du dein Profil und je nach Haushaltssituation auch die
              zugehörigen Familiendaten DSGVO-konform löschen. Aktive
              Notdienst-Verpflichtungen blockieren die Löschung.
            </p>
          </div>
          <DeleteAccountDialog />
        </CardContent>
      </Card>
    </div>
  );
}
