import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import { headers } from "next/headers";
import { getPayload } from "payload";
import config from "@payload-config";
import { PageHeader } from "@/components/PageHeader";
import { Section } from "@/components/Section";
import { ImagePlaceholder } from "@/components/ImagePlaceholder";
import { RichText } from "@/components/RichText";
import { CTA } from "@/components/CTA";
import { RegisterForm } from "@/components/meeting/RegisterForm";
import { getEventBySlug } from "@/lib/payload/content";
import { mediaAlt, mediaUrl } from "@/lib/payload/media";
import { formatFullDate, formatTimeRange } from "@/lib/format";
import { EVENT_CATEGORIES } from "@/collections/Events";
import { canJoinMeeting, combineDateAndTime, getMeetingStatus, statusLabel } from "@/lib/meeting/status";

export const dynamic = "force-dynamic";

type Args = { params: Promise<{ slug: string }> };

export async function generateMetadata({ params }: Args): Promise<Metadata> {
  const { slug } = await params;
  const event = await getEventBySlug(slug);
  if (!event) return {};
  return { title: event.title };
}

export default async function EventDetailPage({ params }: Args) {
  const { slug } = await params;
  const event = await getEventBySlug(slug);
  if (!event) notFound();

  const categoryLabel = EVENT_CATEGORIES.find((c) => c.value === event.category)?.label;
  const time = formatTimeRange(event.startTime, event.endTime);

  let meetingCard = null;
  if (event.isOnline) {
    const payload = await getPayload({ config });
    const { user } = await payload.auth({ headers: await headers() });
    // Must check the collection, not just presence — a logged-in customer
    // (collection "customers") must never be treated as host.
    const isHost = user?.collection === "users";
    const settings = await payload.findGlobal({ slug: "meeting-settings" });
    const start = combineDateAndTime(event.date, event.startTime);
    const end = event.endTime
      ? combineDateAndTime(event.date, event.endTime)
      : new Date(start.getTime() + 60 * 60_000);
    const status = getMeetingStatus({
      start,
      end,
      joinWindowMinutes: isHost ? settings.hostJoinWindowMinutes : settings.participantJoinWindowMinutes,
      closeAfterMinutes: settings.meetingCloseAfterMinutes,
    });
    const joinable = canJoinMeeting(status);

    meetingCard = (
      <div className="rounded-3xl bg-anouma-plum p-6 text-center text-anouma-cream-light">
        <p className="text-xs font-medium uppercase tracking-[0.18em] text-anouma-cream-light/80">
          Online-Termin
        </p>
        {joinable ? (
          <Link
            href={`/termine/${slug}/beitreten`}
            className="mt-4 inline-flex w-full items-center justify-center rounded-full bg-white px-6 py-3 text-sm font-medium text-anouma-plum hover:bg-anouma-cream-light"
          >
            {statusLabel[status]}
          </Link>
        ) : (
          <p className="mt-4 text-base">{statusLabel[status]}</p>
        )}
      </div>
    );
  }

  return (
    <>
      <PageHeader
        eyebrow={categoryLabel}
        title={event.title}
        crumbs={[{ title: "Termine", href: "/termine" }, { title: event.title }]}
      />
      <Section tone="plain">
        <div className="grid gap-14 lg:grid-cols-[1fr_0.8fr]">
          <div className="order-2 lg:order-1 space-y-10">
            {event.description && <RichText data={event.description} />}
            {event.registrationRequired && (
              <div>
                <h2 className="font-serif text-2xl font-medium text-anouma-plum">Anmeldung</h2>
                <div className="mt-4 max-w-sm">
                  <RegisterForm slug={slug} />
                </div>
              </div>
            )}
          </div>
          <div className="order-1 space-y-6 lg:order-2">
            {meetingCard}
            <div className="relative aspect-[4/3] w-full">
              <ImagePlaceholder
                mood="rose"
                label={event.title}
                src={mediaUrl(event.image, "card")}
                alt={mediaAlt(event.image) ?? event.title}
                className="h-full w-full"
              />
            </div>
            <dl className="space-y-3 rounded-3xl bg-anouma-cream-light p-6 text-sm">
              <div>
                <dt className="font-medium uppercase tracking-wide text-anouma-plum/70">Datum</dt>
                <dd className="text-base text-anouma-plum">{formatFullDate(event.date)}</dd>
              </div>
              {time && (
                <div>
                  <dt className="font-medium uppercase tracking-wide text-anouma-plum/70">Uhrzeit</dt>
                  <dd className="text-base text-anouma-plum">{time}</dd>
                </div>
              )}
              {event.location && (
                <div>
                  <dt className="font-medium uppercase tracking-wide text-anouma-plum/70">Ort</dt>
                  <dd className="text-base text-anouma-plum">{event.location}</dd>
                </div>
              )}
              {event.maxParticipants && (
                <div>
                  <dt className="font-medium uppercase tracking-wide text-anouma-plum/70">
                    Teilnehmerzahl
                  </dt>
                  <dd className="text-base text-anouma-plum">max. {event.maxParticipants}</dd>
                </div>
              )}
              {event.registrationRequired && event.registrationInfo && (
                <div>
                  <dt className="font-medium uppercase tracking-wide text-anouma-plum/70">
                    Anmeldung
                  </dt>
                  <dd className="text-base text-anouma-plum">{event.registrationInfo}</dd>
                </div>
              )}
            </dl>
          </div>
        </div>
      </Section>
      <CTA
        title="Dabei sein?"
        lead={`Melde dich gerne für „${event.title}“ an oder frag nach freien Plätzen.`}
      />
    </>
  );
}
