import Image from "next/image";
import Link from "next/link";
import type { ReactNode } from "react";
import { notFound } from "next/navigation";
import { ApiError } from "@/lib/api/server";
import { getMyTicketDetail } from "@/lib/api/tickets";
import { EVENT_STATUS_LABEL } from "@/lib/labels";
import { formatCurrency, formatDate, formatTime } from "@/lib/format";
import { buttonClasses } from "@/components/ui/button";
import { FOCUS_RING_CLASSES } from "@/components/ui/styles";
import { cn } from "@/lib/utils";
import { TicketStatusBadge } from "@/components/tickets/TicketStatusBadge";
import { PaymentStatusBadge } from "@/components/tickets/PaymentStatusBadge";
import { TicketTypeBadge } from "@/components/tickets/TicketTypeBadge";
import { InfoField } from "@/components/tickets/InfoField";
import { DownloadTicketButton } from "@/components/tickets/DownloadTicketButton";
import { PaymentInstructions } from "@/components/checkout/payment/payment-instructions";

function Section({
  title,
  action,
  children,
}: {
  title: string;
  action?: ReactNode;
  children: ReactNode;
}) {
  return (
    <div className="border-t border-dashed border-kolabora-neutral-dark/20 p-6">
      <div className="flex items-center justify-between">
        <h2 className="font-semibold">{title}</h2>
        {action}
      </div>
      <div className="mt-4 grid grid-cols-2 gap-x-4 gap-y-5 sm:grid-cols-3">{children}</div>
    </div>
  );
}

export default async function TicketDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  const ticket = await getMyTicketDetail(id)
    .then((res) => res.data)
    .catch((error) => {
      if (error instanceof ApiError && (error.status === 404 || error.status === 403)) {
        notFound();
      }
      throw error;
    });

  const isPending = ticket.status === "pending";
  const qrHint = isPending
    ? "Complete your payment first to access the ticket."
    : ticket.status === "paid" || ticket.status === "checked_in"
      ? "Ticket is ready to use."
      : "QR code will be available once the ticket is active.";

  return (
    <div className="mx-auto max-w-3xl overflow-hidden rounded-3xl border border-kolabora-neutral-dark/10">
      {/* Header */}
      <div className="flex items-center justify-between border-b border-dashed border-kolabora-neutral-dark/20 px-6 py-4">
        <div className="flex items-center gap-3">
          <Link
            href="/dashboard/tickets"
            aria-label="Back to My Tickets"
            className={cn("rounded p-1 transition-colors hover:bg-kolabora-neutral-dark/5", FOCUS_RING_CLASSES)}
          >
            &larr;
          </Link>
          <Image src="/kolabora-mark.svg" alt="Kolaborativ" width={36} height={28} priority />
        </div>
        <span className="text-sm font-medium text-kolabora-neutral-dark/60">Ticket Detail</span>
      </div>

      {/* Hero: banner + event name/status + ticket type */}
      <div className="p-6">
        {ticket.event.banner ?? ticket.event.thumbnail ? (
          // eslint-disable-next-line @next/next/no-img-element -- organizer-uploaded file, not on next/image allowlist
          <img
            src={ticket.event.banner ?? ticket.event.thumbnail ?? undefined}
            alt={ticket.event.title}
            className="h-48 w-full rounded-xl object-cover"
          />
        ) : (
          <div className="flex h-48 w-full items-center justify-center rounded-xl bg-kolabora-neutral-dark/5 text-sm text-kolabora-neutral-dark/40">
            {ticket.event.title}
          </div>
        )}
        <div className="mt-4 flex flex-wrap items-center justify-between gap-2">
          <div className="min-w-0">
            <p className="truncate font-semibold">{ticket.event.title}</p>
            <p className="text-sm text-kolabora-neutral-dark/70">
              {EVENT_STATUS_LABEL[ticket.event.status] ?? ticket.event.status}
            </p>
          </div>
          <TicketTypeBadge name={ticket.ticket_type.name} />
        </div>
      </div>

      <Section title="Event Information">
        <InfoField label="Organizer" value={ticket.event.organizer_name} />
        <InfoField label="Venue" value={ticket.event.location ?? "-"} />
        <InfoField label="Full Address" value={ticket.event.address ?? "-"} />
        <InfoField label="Date" value={formatDate(ticket.event.start_date)} />
        <InfoField label="Time" value={formatTime(ticket.event.start_date)} />
        {ticket.event.gate && <InfoField label="Gate" value={ticket.event.gate} />}
        {ticket.event.zone && <InfoField label="Zone" value={ticket.event.zone} />}
      </Section>

      <Section title="Ticket Information">
        <InfoField label="Ticket ID" value={ticket.ticket_code} />
        <InfoField label="Ticket Type" value={ticket.ticket_type.name} />
        <InfoField label="Price" value={formatCurrency(ticket.ticket_type.price)} />
        <InfoField label="Order ID" value={String(ticket.order.id)} />
        <InfoField label="Invoice" value={ticket.order.order_number} />
        <InfoField label="Purchase Date" value={formatDate(ticket.order.created_at)} />
      </Section>

      <Section title="Participant Information">
        <InfoField label="Name" value={ticket.holder_name} />
        <InfoField label="Email" value={ticket.holder_email ?? "-"} />
        <InfoField label="Phone Number" value={ticket.holder_phone ?? "-"} />
      </Section>

      <Section title="Payment Information" action={ticket.payment && <PaymentStatusBadge status={ticket.payment.status} />}>
        <InfoField label="Payment Method" value={ticket.payment?.payment_method ?? "-"} />
        <InfoField label="Paid On" value={ticket.payment?.paid_at ? formatDate(ticket.payment.paid_at) : "-"} />
      </Section>

      {/* Pending: show the actual in-progress payment (method-specific — VA
          number/QRIS) plus its countdown to expiry, instead of pretending a
          ticket exists to access yet — same PaymentInstructions component the
          checkout flow itself uses, so the two never drift out of sync. */}
      {isPending && ticket.payment && (
        <div className="border-t border-dashed border-kolabora-neutral-dark/20 p-6">
          <PaymentInstructions payment={ticket.payment} />
        </div>
      )}

      <div className="flex flex-col items-center gap-2 border-t border-dashed border-kolabora-neutral-dark/20 p-6 text-center">
        <TicketStatusBadge status={ticket.status} />
        <p className="text-sm text-kolabora-neutral-dark/70">{qrHint}</p>
      </div>

      <div className="flex flex-col gap-3 border-t border-dashed border-kolabora-neutral-dark/20 p-6 sm:flex-row">
        {isPending ? (
          <Link
            href={`/checkout/status?order=${ticket.order.id}`}
            className={buttonClasses("primary", "md", "w-full")}
          >
            Continue Payment
          </Link>
        ) : (
          <>
            <DownloadTicketButton ticketId={ticket.id} />
            <Link
              href={`/dashboard/tickets/${ticket.id}/e-ticket`}
              className={buttonClasses("primary", "md", "w-full sm:w-auto")}
            >
              View E-Ticket
            </Link>
          </>
        )}
      </div>

      <p className="border-t border-dashed border-kolabora-neutral-dark/20 py-3 text-center text-xs text-kolabora-neutral-dark/40">
        Powered by Kolaborativ
      </p>
    </div>
  );
}
