import Link from "next/link";
import { UserRole } from "@prisma/client";
import { Info, Calendar, ArrowRight, ShieldAlert } from "lucide-react";

import { requireRole } from "@/lib/auth-utils";
import { prisma } from "@/lib/prisma";
import { getTargetMonthData } from "@/lib/date-utils";
import { Button } from "@/components/ui/button";
import { NotdienstEntry } from "./notdienst-entry";

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

export default async function NotdienstPage() {
  // ELTERN können eintragen; Admins/Koordinatoren haben hier eigentlich
  // andere Ansichten (Plan-Generierung), aber wir lassen sie zur Demonstration
  // ebenfalls durch, falls sie selbst Kinder haben.
  const session = await requireRole([
    UserRole.ELTERN,
    UserRole.ADMIN,
    UserRole.KOORDINATOR,
  ]);

  const kitaId = session.user.kitaId;
  if (!kitaId) {
    return <div className="p-8">Kein Mandant zugeordnet.</div>;
  }

  // Kita-Einstellungen laden
  const kita = await prisma.kita.findUniqueOrThrow({
    where: { id: kitaId },
    select: { notdienstMinPerChildPerMonth: true },
  });

  // Nur aktive Kinder des eigenen Haushalts laden.
  const children = session.user.familyId
    ? await prisma.child.findMany({
        where: {
          kitaId,
          familyId: session.user.familyId,
          active: true,
        },
        select: { id: true, firstName: true },
      })
    : [];

  const targetData = getTargetMonthData();
  const { targetYear, targetMonth, monthName, isLocked } = targetData;

  const requiredDaysTotal = children.length * kita.notdienstMinPerChildPerMonth;
  const childIds = children.map((child) => child.id);

  // Bisherige Einträge für den Zielmonat laden, haushaltsweit über die Kinder.
  const [availabilities, availabilityCountForCurrentOrNextMonth] =
    children.length > 0
      ? await Promise.all([
          prisma.notdienstAvailability.findMany({
            where: {
              kitaId,
              childId: { in: childIds },
              date: {
                gte: new Date(targetYear, targetMonth - 1, 1),
                lt: new Date(targetYear, targetMonth, 1),
              },
            },
            select: { date: true },
          }),
          prisma.notdienstAvailability.count({
            where: {
              kitaId,
              childId: { in: childIds },
              date: {
                gte: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
                lt: new Date(new Date().getFullYear(), new Date().getMonth() + 2, 1),
              },
            },
          }),
        ])
      : [[], 0];

  const selectedDates = availabilities.map((a) => a.date.toISOString());

  return (
    <div className="mx-auto max-w-4xl px-4 py-8 sm:px-8">
      <div className="mb-6 flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight flex items-center gap-2">
            <Calendar className="h-6 w-6 text-primary" />
            Notdienst planen
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Gib hier an, an welchen Tagen du im Notdienst unterstützen kannst.
          </p>
        </div>
        <div className="flex flex-col items-start gap-1 sm:items-end">
          <span className="rounded-full bg-primary/10 px-3 py-1 text-sm font-medium text-primary">
            Zielmonat: {monthName}
          </span>
          {isLocked && (
            <span className="text-xs font-medium text-destructive flex items-center gap-1">
              <Info className="h-3 w-3" />
              Eingabefrist abgelaufen
            </span>
          )}
        </div>
      </div>

      {children.length === 0 ? (
        <NotdienstLockout />
      ) : (
        <NotdienstEntry
          hasAnyAvailability={availabilityCountForCurrentOrNextMonth > 0}
          targetYear={targetYear}
          targetMonth={targetMonth}
          isLocked={isLocked}
          requiredDaysTotal={requiredDaysTotal}
          initialSelectedDates={selectedDates}
          childrenIds={childIds}
        />
      )}
    </div>
  );
}

function NotdienstLockout() {
  return (
    <div className="flex min-h-[420px] items-center justify-center rounded-lg border border-dashed bg-muted/20 p-8 text-center">
      <div className="mx-auto max-w-lg">
        <div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full bg-amber-100 text-amber-700 shadow-sm">
          <ShieldAlert className="h-10 w-10" />
        </div>
        <h2 className="mt-6 text-2xl font-semibold tracking-tight">
          Erst Kinder hinterlegen
        </h2>
        <p className="mt-3 text-sm leading-6 text-muted-foreground">
          Bitte lege zuerst deine Kinder im Profil an, bevor du Notdienste
          übernimmst.
        </p>
        <Button asChild className="mt-6">
          <Link href="/dashboard/profil">
            Zum Profil
            <ArrowRight className="h-4 w-4" />
          </Link>
        </Button>
      </div>
    </div>
  );
}
