import type { Metadata } from "next";
import Link from "next/link";
import { getCurrentCustomer } from "@/lib/auth/customer";
import { getCustomerBookings } from "@/lib/booking/queries";
import { BookingCard } from "@/components/booking/BookingCard";

export const metadata: Metadata = { title: "Mein Konto" };

export default async function KontoOverviewPage() {
  const customer = await getCurrentCustomer();
  if (!customer) return null; // Layout already redirects; keeps TS happy.

  const bookings = await getCustomerBookings(customer.id);
  const pending = bookings.filter((b) => b.status === "pending");
  const confirmed = bookings.filter((b) => b.status === "confirmed" && new Date(b.date) >= new Date());
  const past = bookings.filter((b) => new Date(b.date) < new Date() || b.status === "rejected" || b.status === "cancelled");

  return (
    <div className="space-y-10">
      <div className="rounded-3xl bg-white p-6">
        <h2 className="font-serif text-xl font-medium text-anouma-plum">Deine Daten</h2>
        <dl className="mt-4 grid gap-4 sm:grid-cols-2">
          <div>
            <dt className="text-xs font-medium uppercase tracking-wide text-anouma-plum/60">Name</dt>
            <dd className="text-base text-anouma-plum">{customer.name}</dd>
          </div>
          <div>
            <dt className="text-xs font-medium uppercase tracking-wide text-anouma-plum/60">E-Mail</dt>
            <dd className="text-base text-anouma-plum">{customer.email}</dd>
          </div>
        </dl>
      </div>

      <div>
        <div className="flex items-center justify-between">
          <h2 className="font-serif text-xl font-medium text-anouma-plum">Offene Buchungsanfragen</h2>
        </div>
        {pending.length === 0 ? (
          <p className="mt-3 text-sm text-anouma-plum/70">Keine offenen Anfragen.</p>
        ) : (
          <div className="mt-4 grid gap-4 sm:grid-cols-2">
            {pending.map((b) => (
              <BookingCard key={b.id} booking={b} />
            ))}
          </div>
        )}
      </div>

      <div>
        <h2 className="font-serif text-xl font-medium text-anouma-plum">Bestätigte Termine</h2>
        {confirmed.length === 0 ? (
          <p className="mt-3 text-sm text-anouma-plum/70">Noch keine bestätigten Termine.</p>
        ) : (
          <div className="mt-4 grid gap-4 sm:grid-cols-2">
            {confirmed.map((b) => (
              <BookingCard key={b.id} booking={b} />
            ))}
          </div>
        )}
      </div>

      {past.length > 0 && (
        <div>
          <Link href="/konto/termine" className="text-sm font-medium text-anouma-mauve-dark underline underline-offset-4">
            Alle Termine (inkl. vergangene) ansehen →
          </Link>
        </div>
      )}
    </div>
  );
}
