import Link from "next/link";
import { notFound } from "next/navigation";
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";

/**
 * "main event.png" wireframe order: Thumbnail+Logo, Promo/Voucher reminder
 * cards, Deskripsi+Denah, Rules+ticket tiers (one panel per ticket_types row).
 * 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 ?? [];

  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-cream 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>

      {/* Promo & Voucher reminders — free-text content set by Admin on the
          dedicated Signature admin page, not connected to the real
          Promo/Voucher module (deliberate 2026-07-23 decision). Falls back
          to generic teaser copy when Admin hasn't set anything yet. */}
      <section className="mx-auto grid max-w-3xl grid-cols-1 gap-4 px-6 py-12 sm:grid-cols-2 lg:max-w-5xl xl:max-w-6xl 2xl:max-w-7xl">
        <div className="flex min-h-40 flex-col items-center justify-center rounded-2xl bg-signaturee-yellow/30 p-6 text-center">
          <p className="font-signaturee text-lg font-semibold text-signaturee-red">Promo &amp; Voucher</p>
          <p className="mt-2 whitespace-pre-line text-sm text-neutral-600">
            {event.signature_profile?.promo_text || "Stay tuned for the latest promo & voucher codes for this event."}
          </p>
        </div>
        <div className="flex min-h-40 flex-col items-center justify-center rounded-2xl bg-signaturee-orange/15 p-6 text-center">
          <p className="font-signaturee text-lg font-semibold text-signaturee-red">Promo Spesial</p>
          <p className="mt-2 whitespace-pre-line text-sm text-neutral-600">
            {event.signature_profile?.promo_special_text || "A special promo is coming — announced soon."}
          </p>
        </div>
      </section>

      {/* Deskripsi + Denah */}
      <section className="mx-auto grid max-w-3xl grid-cols-1 gap-4 px-6 py-12 sm:grid-cols-2 lg:max-w-5xl xl:max-w-6xl 2xl:max-w-7xl">
        <div className="flex min-h-64 flex-col justify-center rounded-2xl bg-signaturee-cream p-6">
          <p className="font-signaturee text-lg font-semibold text-signaturee-red">About the Event</p>
          <p className="mt-3 whitespace-pre-line text-sm text-neutral-700">
            {/* Deliberately independent from event.description (shown on the main
                /events/{slug} page) — falls back to it only when Admin hasn't set
                a dedicated detail-page copy yet, per explicit user decision 2026-07-23. */}
            {event.signature_profile?.about_text || event.description || "Event description coming soon."}
          </p>
        </div>
        <div className="flex min-h-64 flex-col overflow-hidden rounded-2xl bg-signaturee-red text-signaturee-cream">
          <p className="px-5 pt-5 font-signaturee text-lg font-semibold">Venue Map</p>
          {/* 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="mt-3 w-full flex-1 object-contain"
          />

        </div>
      </section>

      {/* Rules + ticket tiers */}
      <section className="mx-auto grid max-w-3xl grid-cols-1 gap-4 px-6 pb-16 sm:grid-cols-2 lg:max-w-5xl xl:max-w-6xl 2xl:max-w-7xl">
        <div className="flex min-h-96 flex-col rounded-2xl bg-neutral-100 p-6">
          <p className="font-signaturee text-lg font-semibold text-signaturee-red">Rules</p>
          {event.signature_profile?.rules && event.signature_profile.rules.length > 0 ? (
            <ul className="mt-3 list-disc space-y-1.5 pl-5 text-sm text-neutral-600">
              {event.signature_profile.rules.map((rule, index) => (
                <li key={index}>{rule}</li>
              ))}
            </ul>
          ) : (
            <p className="mt-3 text-sm text-neutral-600">Event rules will be announced soon.</p>
          )}
        </div>

        <div className="flex flex-col gap-4">
          {ticketTypes.map((tt) => (
            <TicketCategoryPanel key={tt.id} slug={slug} label={tt.name} tickets={[tt]} />
          ))}
        </div>
      </section>
    </div>
  );
}

function TicketCategoryPanel({
  slug,
  label,
  tickets,
}: {
  slug: string;
  label: string;
  tickets: TicketType[];
}) {
  if (tickets.length === 0) return null;

  return (
    <div className="flex flex-col gap-3 rounded-2xl bg-neutral-100 p-4">
      <p className="text-sm font-medium text-neutral-500">{label}</p>
      <div className="flex flex-1 flex-col gap-2">
        {tickets.map((tt) =>
          (tt.phases ?? [])
            .filter((phase) => phase.status !== "closed")
            .map((phase) => {
              const content = (
                <>
                  <span className="min-w-0 truncate text-sm font-medium">
                    {tt.name} &mdash; {phase.name}
                  </span>
                  <span className="flex shrink-0 items-center gap-2">
                    {phase.status === "coming_soon" && (
                      <span className="rounded-full bg-yellow-400 px-2 py-0.5 text-xs font-medium text-yellow-950">
                        Coming Soon
                      </span>
                    )}
                    {phase.status === "sold_out" && (
                      <span className="rounded-full bg-red-600 px-2 py-0.5 text-xs font-medium text-white">
                        Sold Out
                      </span>
                    )}
                    <span className="text-sm font-semibold">{formatCurrency(phase.price)}</span>
                  </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-neutral-300 px-4 py-3 transition-opacity hover:opacity-80"
                >
                  {content}
                </Link>
              ) : (
                <div
                  key={phase.id}
                  className="flex items-center justify-between gap-3 rounded-xl bg-neutral-300/50 px-4 py-3 opacity-70"
                >
                  {content}
                </div>
              );
            }),
        )}
      </div>
    </div>
  );
}
