"use client";

import { useTransition } from "react";
import { format } from "date-fns";
import { de } from "date-fns/locale";
import { CalendarIcon, Check, Clock, X } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { approveTermin, rejectTermin } from "../actions";

export type PendingTerminDto = {
  id: string;
  title: string;
  startDate: Date;
  createdAt: Date;
  ageInDays: number;
  allDay: boolean;
  createdBy: { firstName: string; lastName: string } | null;
};

export function PendingAnfragen({ termine }: { termine: PendingTerminDto[] }) {
  if (termine.length === 0) {
    return (
      <Card>
        <CardContent className="flex max-h-[280px] min-h-[260px] flex-col items-center justify-center p-8 text-center animate-in fade-in-50">
          <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--accent-soft)] text-[var(--accent-deep)]">
            <CalendarIcon className="h-6 w-6 [stroke-width:1.7]" />
          </div>
          <h3 className="text-lg font-medium text-[var(--ink)]">
            Keine ausstehenden Anfragen
          </h3>
          <p className="mt-2 text-sm text-[var(--ink-soft)]">
            Es gibt aktuell keine Terminanfragen, die bestätigt werden müssen.
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="overflow-hidden p-0">
      {termine.map((termin) => (
        <PendingTerminCard key={termin.id} termin={termin} />
      ))}
    </Card>
  );
}

function PendingTerminCard({ termin }: { termin: PendingTerminDto }) {
  const [isPending, startTransition] = useTransition();

  const handleApprove = () => {
    startTransition(async () => {
      const res = await approveTermin(termin.id);
      if (res.error) {
        toast.error(res.error);
      } else {
        toast.success("Anfrage freigegeben.");
      }
    });
  };

  const handleReject = () => {
    // In a real app, you might want to ask for a rejection reason in a prompt/modal.
    startTransition(async () => {
      const res = await rejectTermin(termin.id);
      if (res.error) {
        toast.error(res.error);
      } else {
        toast.success("Anfrage abgelehnt.");
      }
    });
  };

  return (
    <div className="grid grid-cols-[56px_minmax(0,1fr)_auto] items-center gap-4 border-b border-[var(--hairline-soft)] px-5 py-4 last:border-b-0 hover:bg-[var(--surface-2)]">
      <div className="flex h-14 w-14 flex-col items-center justify-center rounded-lg border border-[var(--hairline)] bg-[var(--surface-2)]">
        <span className="text-[22px] font-medium leading-none tracking-[-0.02em] text-[var(--ink)] tabular-nums">
          {format(termin.startDate, "d", { locale: de })}
        </span>
        <span className="mt-1 text-[10px] font-semibold uppercase text-[var(--ink-muted)] [letter-spacing:0.08em]">
          {format(termin.startDate, "EEE", { locale: de })}
        </span>
      </div>

      <div className="min-w-0">
        <div className="flex flex-wrap items-center gap-2">
          <h3 className="truncate text-[15px] font-semibold text-[var(--ink)]">
            {termin.title}
          </h3>
          {termin.ageInDays > 7 && (
            <Badge variant="warning">Älter als 7 Tage</Badge>
          )}
        </div>
        <p className="mt-1 flex items-center gap-1 text-sm text-[var(--ink-soft)]">
          <Clock className="h-3.5 w-3.5 [stroke-width:1.7]" />
          {format(termin.startDate, "PP", { locale: de })}
          {!termin.allDay &&
            ` · ${format(termin.startDate, "p", { locale: de })}`}
        </p>
        <p className="mt-1 text-sm font-medium text-[var(--accent-deep)]">
          Angefragt von: {termin.createdBy?.firstName}{" "}
          {termin.createdBy?.lastName} · vor {termin.ageInDays} Tagen
        </p>
      </div>

      <div className="flex flex-col gap-2 sm:flex-row">
        <Button
          variant="ghost"
          size="sm"
          className="text-[var(--danger)] hover:bg-[var(--danger-soft)] hover:text-[var(--danger)]"
          onClick={handleReject}
          disabled={isPending}
        >
          <X className="h-4 w-4 [stroke-width:1.7]" />
          Ablehnen
        </Button>
        <Button
          size="sm"
          onClick={handleApprove}
          disabled={isPending}
        >
          <Check className="h-4 w-4 [stroke-width:1.7]" />
          Genehmigen
        </Button>
      </div>
    </div>
  );
}
