import Link from "next/link";
import { notFound } from "next/navigation";
import type { ReactNode } from "react";
import { ApiError } from "@/lib/api/server";
import { getEventBySlug } from "@/lib/api/events";
import { formatCurrency } from "@/lib/format";
import type { TicketType } from "@/types/event";
import { SignatureCustomCursor } from "@/components/events/signature/SignatureCustomCursor";

/**
 * "detaileventpage.webp" layout: Thumbnail+Logo, then a two-column
 * yellow-themed section — left: About Event (Deskripsi + Ketentuan Tiket +
 * Rules), right: Venue + one "Jenis Tiket" card per ticket type. Promo &
 * Voucher cards removed 2026-08-07 — no longer part of the design.
 * Destination for the "Full card event" thumbnail on the Signature Event
 * page (`SignatureEventCard`).
 */
export default async function EventDetailExtraPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;

  const event = await getEventBySlug(slug)
    .then((res) => res.data)
    .catch((error) => {
      if (error instanceof ApiError && error.status === 404) {
        notFound();
      }
      throw error;
    });

  // Each `ticket_types` row already IS a category (admin names it directly,
  // e.g. "Festival"/"Picnic"/anything else) — no need to bucket by name.
  const ticketTypes = event.ticket_types ?? [];
  const ticketTypesWithTerms = ticketTypes.filter((tt) => tt.terms?.length > 0);

  return (
    <div>
      <SignatureCustomCursor />
      <div className="px-6 pt-6">
        <Link href={`/events/${slug}`} className="text-sm font-medium text-kolabora-primary">
          &larr; Back to Event
        </Link>
      </div>

      {/* Thumbnail + Logo */}
      <section className="bg-signaturee-yellow px-6 py-12">
        <div className="mx-auto max-w-3xl overflow-hidden rounded-3xl bg-neutral-200 lg:max-w-5xl xl:max-w-6xl 2xl:max-w-7xl">
          {event.signature_profile?.detail_thumbnail_url ? (
            // eslint-disable-next-line @next/next/no-img-element -- organizer-uploaded file, not on next/image allowlist
            <img
              src={event.signature_profile.detail_thumbnail_url}
              alt={event.title}
              className="aspect-video w-full object-cover"
            />
          ) : (
            <div className="flex aspect-video w-full items-center justify-center text-sm text-neutral-500">
              Thumbnail coming soon
            </div>
          )}
        </div>
      </section>

      {/* About Event / Venue — two-column layout per detaileventpage.webp */}
      <section className="relative overflow-hidden bg-signaturee-yellow px-6 py-12">
        {/* Decorative blobs — reuse of the same flower asset SignatureAbout.tsx
            uses (public/brand/signaturee-about-flower.svg), not new artwork. */}
        {/* eslint-disable-next-line @next/next/no-img-element -- decorative static brand asset */}
        <img
          src="/brand/signaturee-about-flower.svg"
          alt=""
          aria-hidden="true"
          className="pointer-events-none absolute -top-24 -right-24 h-80 w-80 opacity-60 sm:h-[28rem] sm:w-[28rem]"
        />
        {/* eslint-disable-next-line @next/next/no-img-element -- decorative static brand asset */}
        <img
          src="/brand/signaturee-about-flower.svg"
          alt=""
          aria-hidden="true"
          className="pointer-events-none absolute -bottom-32 -left-24 h-72 w-72 opacity-50 sm:h-96 sm:w-96"
        />

        <div className="relative mx-auto grid max-w-3xl grid-cols-1 gap-6 sm:grid-cols-2 lg:max-w-5xl xl:max-w-6xl 2xl:max-w-7xl">
          {/* Left column: About Event */}
          <div className="flex flex-col gap-6">
            <PillHeader tone="cream">About Event</PillHeader>

            <div className="rounded-3xl bg-signaturee-cream p-6">
              <h3 className="font-signaturee text-xl font-bold text-signaturee-blue-light">Deskripsi</h3>
              <p className="mt-2 whitespace-pre-line text-sm text-signaturee-blue-light/90">
                {event.signature_profile?.about_text || event.description || "Event description coming soon."}
              </p>

              {ticketTypesWithTerms.length > 0 && (
                <>
                  <h3 className="mt-6 font-signaturee text-xl font-bold text-signaturee-blue-light">
                    Ketentuan Tiket
                  </h3>
                  {ticketTypesWithTerms.map((tt) => (
                    <div key={tt.id} className="mt-3">
                      <p className="font-semibold text-signaturee-blue-light">Tiket {tt.name}</p>
                      <ol className="mt-1 list-decimal space-y-1 pl-5 text-sm text-signaturee-blue-light/90">
                        {(tt.terms ?? []).map((term, index) => (
                          <li key={index}>{term}</li>
                        ))}
                      </ol>
                    </div>
                  ))}
                </>
              )}
            </div>

            <div className="rounded-3xl bg-signaturee-cream p-6">
              <h3 className="font-signaturee text-xl font-bold text-signaturee-blue-light">Rules</h3>
              {event.signature_profile?.rules && event.signature_profile.rules.length > 0 ? (
                <ol className="mt-3 list-decimal space-y-1.5 pl-5 text-sm text-signaturee-blue-light/90">
                  {event.signature_profile.rules.map((rule, index) => (
                    <li key={index}>{rule}</li>
                  ))}
                </ol>
              ) : (
                <p className="mt-3 text-sm text-signaturee-blue-light/90">Event rules will be announced soon.</p>
              )}
            </div>
          </div>

          {/* Right column: Venue + ticket type cards */}
          <div className="flex flex-col gap-6">
            <PillHeader tone="orange">Venue</PillHeader>

            <div className="overflow-hidden rounded-3xl bg-signaturee-orange p-6">
              {/* eslint-disable-next-line @next/next/no-img-element -- admin-uploaded file (or static fallback), not on next/image allowlist */}
              <img
                src={event.signature_profile?.denah_image_url || "/brand/denah-konser.svg"}
                alt="Venue map"
                className="w-full object-contain"
              />
            </div>

            {ticketTypes.map((tt) => (
              <TicketCategoryPanel key={tt.id} slug={slug} ticket={tt} />
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

function PillHeader({ tone, children }: { tone: "cream" | "orange"; children: ReactNode }) {
  return (
    <div
      className={
        tone === "cream"
          ? "inline-block w-fit rounded-2xl bg-signaturee-cream-light px-6 py-3 font-signaturee text-2xl font-bold uppercase tracking-wide text-signaturee-blue-light"
          : "inline-block w-fit rounded-2xl bg-signaturee-orange px-6 py-3 font-signaturee text-2xl font-bold uppercase tracking-wide text-white"
      }
    >
      {children}
    </div>
  );
}

function TicketCategoryPanel({ slug, ticket }: { slug: string; ticket: TicketType }) {
  return (
    <div className="flex flex-col gap-3 rounded-3xl bg-signaturee-orange p-6">
      <p className="font-signaturee text-lg font-bold uppercase tracking-wide text-white">{ticket.name}</p>
      <div className="flex flex-1 flex-col gap-2">
        {(ticket.phases ?? [])
          .filter((phase) => phase.status !== "closed")
          .map((phase) => {
            const content = (
              <>
                <span className="min-w-0 truncate text-sm font-medium text-signaturee-blue-light">
                  {phase.name}
                </span>
                {/* Price isn't real information yet while the phase hasn't gone
                    on sale — showing it next to a "Coming Soon" stamp reads as
                    a price that's already active. */}
                {phase.status !== "coming_soon" && (
                  <span className="text-sm font-semibold text-signaturee-blue-light">{formatCurrency(phase.price)}</span>
                )}
              </>
            );

            return phase.status === "available" ? (
              <Link
                key={phase.id}
                href={`/events/${slug}/detail/tiket/${phase.id}`}
                className="flex items-center justify-between gap-3 rounded-xl bg-signaturee-cream px-4 py-3 transition-opacity hover:opacity-80"
              >
                {content}
              </Link>
            ) : (
              <div
                key={phase.id}
                className="relative flex items-center justify-between gap-3 overflow-hidden rounded-xl bg-signaturee-cream px-4 py-3"
              >
                <div className="flex flex-1 items-center justify-between gap-3 opacity-40">{content}</div>
                {/* Centered, rotated, oversized stamp — easier to spot at a glance
                    than a small inline pill, per explicit request. */}
                {phase.status === "coming_soon" && (
                  <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 -rotate-6 rounded-md bg-yellow-400 px-3 py-1 text-xs font-bold uppercase tracking-wide text-yellow-950 shadow-md">
                    Coming Soon
                  </span>
                )}
                {phase.status === "sold_out" && (
                  <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 -rotate-6 rounded-md bg-red-600 px-3 py-1 text-xs font-bold uppercase tracking-wide text-white shadow-md">
                    Sold Out
                  </span>
                )}
              </div>
            );
          })}
      </div>
    </div>
  );
}
