"use client";

import Link from "next/link";
import { useMemo, useTransition } from "react";
import { AbsenceReason } from "@prisma/client";
import { Baby, CalendarX2, Loader2, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { deleteAbsence, reportAbsence } 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";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";

type ChildOption = {
  id: string;
  name: string;
};

type AbsenceListItem = {
  id: string;
  childName: string;
  reason: AbsenceReason;
  note: string | null;
  startDate: string;
  endDate: string;
};

export function AbsenceCard({
  childOptions,
  absences,
  today,
}: {
  childOptions: ChildOption[];
  absences: AbsenceListItem[];
  today: string;
}) {
  const [isPending, startTransition] = useTransition();
  const defaultChildId = childOptions[0]?.id;
  const hasChildren = childOptions.length > 0;

  function handleSubmit(formData: FormData) {
    startTransition(async () => {
      const result = await reportAbsence({
        childId: String(formData.get("childId") ?? ""),
        startDate: String(formData.get("startDate") ?? ""),
        endDate: String(formData.get("endDate") ?? ""),
        reason: String(formData.get("reason") ?? ""),
        note: String(formData.get("note") ?? ""),
      });

      if (result.error) {
        toast.error(result.error);
        return;
      }

      toast.success("Abwesenheit eingetragen.");
    });
  }

  function handleDelete(absenceId: string) {
    startTransition(async () => {
      const result = await deleteAbsence(absenceId);
      if (result.error) {
        toast.error(result.error);
        return;
      }

      toast.success("Abwesenheit storniert.");
    });
  }

  return (
    <Card className="mb-8 border-amber-200 bg-amber-50/50">
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-lg">
          <CalendarX2 className="h-5 w-5 text-amber-700" />
          Kind abmelden
        </CardTitle>
        <CardDescription>
          Melde dein Kind für ganze Tage ab. Die Kita sieht die Meldung direkt
          in der Tagesübersicht.
        </CardDescription>
      </CardHeader>
      <CardContent className="grid gap-6 lg:grid-cols-[1.15fr_0.85fr]">
        {hasChildren ? (
          <form action={handleSubmit} className="grid gap-4">
            <div className="grid gap-2">
              <Label>Welches Kind?</Label>
              <Select name="childId" defaultValue={defaultChildId} required>
                <SelectTrigger>
                  <SelectValue placeholder="Kind auswählen" />
                </SelectTrigger>
                <SelectContent>
                  {childOptions.map((child) => (
                    <SelectItem key={child.id} value={child.id}>
                      {child.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="absence-startDate">Von</Label>
                <Input
                  id="absence-startDate"
                  name="startDate"
                  type="date"
                  defaultValue={today}
                  required
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="absence-endDate">Bis</Label>
                <Input
                  id="absence-endDate"
                  name="endDate"
                  type="date"
                  defaultValue={today}
                  required
                />
              </div>
            </div>

            <div className="grid gap-2">
              <Label>Grund</Label>
              <Select name="reason" defaultValue={AbsenceReason.ILLNESS} required>
                <SelectTrigger>
                  <SelectValue placeholder="Grund auswählen" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value={AbsenceReason.ILLNESS}>Krank</SelectItem>
                  <SelectItem value={AbsenceReason.VACATION}>Urlaub</SelectItem>
                  <SelectItem value={AbsenceReason.OTHER}>Sonstiges</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="absence-note">Bemerkung</Label>
              <Textarea
                id="absence-note"
                name="note"
                rows={3}
                placeholder="Optional, z.B. voraussichtlich wieder da am Freitag."
              />
            </div>

            <div className="flex justify-end">
              <Button type="submit" disabled={isPending}>
                {isPending && <Loader2 className="h-4 w-4 animate-spin" />}
                Abwesenheit melden
              </Button>
            </div>
          </form>
        ) : (
          <div className="flex min-h-72 flex-col items-center justify-center rounded-md border border-dashed bg-background/70 p-6 text-center">
            <Baby className="h-10 w-10 text-muted-foreground" />
            <p className="mt-4 font-medium">Noch keine Kinder hinterlegt</p>
            <p className="mt-1 text-sm text-muted-foreground">
              Lege zuerst deine Kinder im Profil an, dann kannst du sie hier
              abmelden.
            </p>
            <Button asChild className="mt-4" variant="outline">
              <Link href="/dashboard/profil">Zum Profil</Link>
            </Button>
          </div>
        )}

        <div className="rounded-md border bg-background/80 p-4">
          <div className="mb-3 flex items-center justify-between gap-3">
            <p className="font-medium">Aktuelle & anstehende Meldungen</p>
            <Badge variant="secondary">{absences.length}</Badge>
          </div>
          {absences.length === 0 ? (
            <p className="text-sm text-muted-foreground">
              Es sind keine aktuellen oder kommenden Abwesenheiten hinterlegt.
            </p>
          ) : (
            <div className="space-y-3">
              {absences.map((absence) => (
                <AbsenceRow
                  key={absence.id}
                  absence={absence}
                  disabled={isPending}
                  onDelete={handleDelete}
                />
              ))}
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

function AbsenceRow({
  absence,
  disabled,
  onDelete,
}: {
  absence: AbsenceListItem;
  disabled: boolean;
  onDelete: (id: string) => void;
}) {
  const range = useMemo(() => {
    const start = new Date(`${absence.startDate}T00:00:00`);
    const end = new Date(`${absence.endDate}T00:00:00`);
    const startLabel = start.toLocaleDateString("de-DE", {
      day: "2-digit",
      month: "2-digit",
    });
    const endLabel = end.toLocaleDateString("de-DE", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
    return absence.startDate === absence.endDate
      ? endLabel
      : `${startLabel} - ${endLabel}`;
  }, [absence.endDate, absence.startDate]);

  return (
    <div className="rounded-md border p-3">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <p className="font-medium">{absence.childName}</p>
          <p className="mt-0.5 text-sm text-muted-foreground">{range}</p>
        </div>
        <Button
          type="button"
          variant="ghost"
          size="icon"
          className="h-8 w-8 shrink-0 text-destructive hover:text-destructive"
          onClick={() => onDelete(absence.id)}
          disabled={disabled}
          aria-label="Abwesenheit stornieren"
        >
          <Trash2 className="h-4 w-4" />
        </Button>
      </div>
      <div className="mt-2 flex flex-wrap items-center gap-2">
        <ReasonBadge reason={absence.reason} />
        {absence.note && (
          <span className="text-xs text-muted-foreground">{absence.note}</span>
        )}
      </div>
    </div>
  );
}

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>;
}
