import Link from "next/link";
import { addDays, format } from "date-fns";
import { de } from "date-fns/locale";
import { ArrowLeft, ArrowRight, CalendarDays, Stethoscope } from "lucide-react";
import { AbsenceReason } from "@prisma/client";

import { getDailyAbsences } from "@/actions/absences";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";

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

export default async function AdminAbwesenheitenPage({
  searchParams,
}: {
  searchParams: { date?: string };
}) {
  const selectedDate = parseDateParam(searchParams.date);
  const dateKey = format(selectedDate, "yyyy-MM-dd");
  const result = await getDailyAbsences({ date: dateKey });
  const absences = result.absences ?? [];

  return (
    <div className="min-h-full bg-slate-50 px-4 py-6 sm:px-8">
      <div className="mx-auto max-w-5xl space-y-6">
        <div className="flex flex-col gap-4 rounded-lg border bg-background p-5 shadow-sm lg:flex-row lg:items-center lg:justify-between">
          <div>
            <div className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
              <Stethoscope className="h-4 w-4" />
              Tagesübersicht
            </div>
            <h1 className="mt-2 text-3xl font-bold tracking-tight">
              Heute fehlen ({absences.length} Kinder)
            </h1>
            <p className="mt-1 text-sm text-muted-foreground">
              {format(selectedDate, "EEEE, dd. MMMM yyyy", { locale: de })}
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2">
            <Button asChild variant="outline" size="sm">
              <Link href={hrefForDate(addDays(selectedDate, -1))}>
                <ArrowLeft className="h-4 w-4" />
                Zurück
              </Link>
            </Button>
            <Button asChild variant="outline" size="sm">
              <Link href="/dashboard/admin/abwesenheiten">Heute</Link>
            </Button>
            <Button asChild variant="outline" size="sm">
              <Link href={hrefForDate(addDays(selectedDate, 1))}>
                Vor
                <ArrowRight className="h-4 w-4" />
              </Link>
            </Button>
            <form className="flex items-center gap-2">
              <Input
                type="date"
                name="date"
                defaultValue={dateKey}
                className="h-9 w-40"
              />
              <Button type="submit" size="sm">
                Anzeigen
              </Button>
            </form>
          </div>
        </div>

        {result.error ? (
          <Card className="border-destructive/30">
            <CardContent className="p-6 text-sm text-destructive">
              {result.error}
            </CardContent>
          </Card>
        ) : absences.length === 0 ? (
          <div className="flex min-h-[420px] items-center justify-center rounded-lg border border-dashed bg-background p-8 text-center">
            <div className="mx-auto max-w-md">
              <div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full bg-emerald-100 text-emerald-700">
                <CalendarDays className="h-10 w-10" />
              </div>
              <h2 className="mt-6 text-2xl font-semibold tracking-tight">
                Keine Abwesenheiten
              </h2>
              <p className="mt-2 text-sm text-muted-foreground">
                Für diesen Tag sind aktuell keine Kinder abgemeldet.
              </p>
            </div>
          </div>
        ) : (
          <div className="grid gap-3">
            {absences.map((absence) => (
              <Card key={absence.id} className="overflow-hidden">
                <CardHeader className="flex flex-col gap-3 p-5 sm:flex-row sm:items-start sm:justify-between">
                  <div>
                    <CardTitle className="text-xl">
                      {absence.childName}
                    </CardTitle>
                    <CardDescription className="mt-1">
                      {absence.familyName}
                    </CardDescription>
                  </div>
                  <ReasonBadge reason={absence.reason} />
                </CardHeader>
                <CardContent className="grid gap-3 px-5 pb-5 sm:grid-cols-[180px_1fr]">
                  <div className="text-sm">
                    <p className="font-medium">Zeitraum</p>
                    <p className="text-muted-foreground">
                      {formatDateRange(absence.startDate, absence.endDate)}
                    </p>
                  </div>
                  <div className="text-sm">
                    <p className="font-medium">Notiz</p>
                    <p className="text-muted-foreground">
                      {absence.note || "Keine Bemerkung hinterlegt."}
                    </p>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function parseDateParam(value: string | undefined) {
  if (!value) return new Date();
  const parsed = new Date(`${value}T00:00:00`);
  return Number.isNaN(parsed.getTime()) ? new Date() : parsed;
}

function hrefForDate(date: Date) {
  return `/dashboard/admin/abwesenheiten?date=${format(date, "yyyy-MM-dd")}`;
}

function formatDateRange(startDate: string, endDate: string) {
  const start = new Date(`${startDate}T00:00:00`);
  const end = new Date(`${endDate}T00:00:00`);
  const startLabel = format(start, "dd.MM.", { locale: de });
  const endLabel = format(end, "dd.MM.yyyy", { locale: de });
  return startDate === endDate ? endLabel : `${startLabel} - ${endLabel}`;
}

function ReasonBadge({ reason }: { reason: AbsenceReason }) {
  if (reason === AbsenceReason.ILLNESS) {
    return <Badge variant="destructive">Krank</Badge>;
  }

  if (reason === AbsenceReason.VACATION) {
    return <Badge variant="warning">Urlaub</Badge>;
  }

  return <Badge variant="outline">Sonstiges</Badge>;
}
