import { requireKitaSession } from "@/lib/auth-utils";
import { prisma } from "@/lib/prisma";
import { format } from "date-fns";
import { de } from "date-fns/locale";
import {
  Baby,
  CalendarHeart,
  Home,
  Mail,
  Phone,
  Shield,
  UserCircle,
} from "lucide-react";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/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 user = await 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,
            },
          },
        },
      },
    },
  });

  return (
    <div className="flex h-full flex-col gap-6 p-6 max-w-4xl mx-auto w-full">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Mein Profil</h1>
        <p className="text-muted-foreground">
          Deine persönlichen Daten, verknüpfte Kinder und DSGVO-Einstellungen.
        </p>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Persönliche Daten */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <UserCircle className="h-5 w-5" />
              Persönliche Daten
            </CardTitle>
          </CardHeader>
          <CardContent className="flex flex-col gap-4">
            <div>
              <div className="text-sm text-muted-foreground">Name</div>
              <div className="font-medium text-lg">
                {user.firstName} {user.lastName}
              </div>
            </div>
            <div>
              <div className="text-sm text-muted-foreground flex items-center gap-1">
                <Mail className="h-3.5 w-3.5" /> E-Mail
              </div>
              <div className="font-medium">{user.email}</div>
            </div>
            <div>
              <div className="text-sm text-muted-foreground flex items-center gap-1">
                <Phone className="h-3.5 w-3.5" /> Telefon
              </div>
              <div className="font-medium">
                {user.phone ?? "Noch nicht hinterlegt"}
              </div>
            </div>
            <div>
              <div className="text-sm text-muted-foreground">Rolle im Verein</div>
              <Badge variant={user.role === "ELTERN" ? "secondary" : "default"} className="mt-1">
                {user.role}
              </Badge>
            </div>
            <div>
              <div className="text-sm text-muted-foreground flex items-center gap-1">
                <Home className="h-3.5 w-3.5" /> Haushalt
              </div>
              {user.family ? (
                <div className="font-medium">{user.family.name}</div>
              ) : (
                <div className="mt-2 space-y-3 rounded-md border border-dashed p-3">
                  <p className="text-sm text-muted-foreground">
                    Dein Account ist noch keinem Haushalt zugeordnet. Lege hier
                    deinen eigenen Haushalt an, wenn du selbst Elternteil in der
                    Kita bist.
                  </p>
                  <CreateFamilyDialog
                    defaultFamilyName={`Familie ${user.lastName}`}
                  />
                </div>
              )}
            </div>
            <div className="pt-2 border-t mt-2">
              <div className="text-sm text-muted-foreground flex items-center gap-1">
                <CalendarHeart className="h-3.5 w-3.5" /> Mitglied seit
              </div>
              <div className="text-sm">
                {format(user.createdAt, "PPP", { locale: de })}
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="flex flex-col gap-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Phone className="h-5 w-5" />
                Kontaktdaten
              </CardTitle>
              <CardDescription>
                Diese Angaben helfen bei Notdienst, Adressbuch und Abstimmung in
                der Kita.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <ContactForm
                contact={{
                  phone: user.phone,
                  street: user.street,
                  postalCode: user.postalCode,
                  city: user.city,
                }}
              />
            </CardContent>
          </Card>

          {/* Kinder */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Baby className="h-5 w-5" />
                Meine Kinder
              </CardTitle>
            </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>

          {/* Ämter */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Shield className="h-5 w-5" />
                Meine Ämter & Dienste
              </CardTitle>
            </CardHeader>
            <CardContent>
              {user.dutyAssignments.length === 0 ? (
                <p className="text-sm text-muted-foreground">Du hast aktuell keine festen Ämter übernommen.</p>
              ) : (
                <div className="flex flex-wrap gap-2">
                  {user.dutyAssignments.map((assignment) => (
                    <Badge key={assignment.id} variant="default" className="text-sm py-1 px-3">
                      {assignment.duty.name}
                    </Badge>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      <Card className="border-destructive/20 mt-8">
        <CardHeader>
          <CardDescription>
            Hier kannst du dein Profil und je nach Haushaltssituation auch die
            zugehörigen Familiendaten DSGVO-konform löschen.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <DeleteAccountDialog />
        </CardContent>
      </Card>

    </div>
  );
}
