import Image from "next/image";
import dynamic from "next/dynamic";
import type { ApiError } from "@alqove/types";
import type { CheckinBrandingData } from "@alqove/api-client";
import { checkinApi } from "@/lib/checkin/api";
import { DeadLinkNotice } from "./DeadLinkNotice";
import { StorePausedNotice } from "./StorePausedNotice";

// Lazy-load the interactive wizard so the branding shell paints with minimal
// JS; the form chunk (TanStack Query + Turnstile) loads after first paint.
const CheckinForm = dynamic(() =>
  import("./CheckinForm").then((m) => ({ default: m.CheckinForm })),
);

// Branding is cacheable but must reflect pause/rotate quickly (D7/D10).
export const revalidate = 30;

interface CheckinPageProps {
  params: Promise<{ token: string }>;
}

function isApiError(err: unknown): err is ApiError {
  return typeof err === "object" && err !== null && "status" in err;
}

function GenericError() {
  return (
    <main className="flex flex-1 items-center justify-center px-6 py-16">
      <div className="max-w-sm text-center">
        <h1 className="text-xl font-semibold text-slate-900">
          Something went wrong
        </h1>
        <p className="mt-3 text-sm text-slate-600">
          We couldn&apos;t load this check-in page. Please try again in a moment.
        </p>
      </div>
    </main>
  );
}

function BrandingHeader({ branding }: { branding: CheckinBrandingData }) {
  return (
    <header className="flex flex-col items-center gap-3 border-b border-slate-200 bg-white px-6 py-6 text-center">
      {branding.logo ? (
        <Image
          src={branding.logo}
          alt={`${branding.name} logo`}
          width={64}
          height={64}
          className="h-16 w-16 rounded-full object-cover"
        />
      ) : null}
      <h1 className="text-lg font-semibold text-slate-900">
        {branding.name}
      </h1>
      {branding.hours ? (
        <p className="text-xs text-slate-500">{branding.hours}</p>
      ) : null}
    </header>
  );
}

/**
 * Public branding shell for the check-in lane (server-rendered, anonymous).
 * Fetches store branding by the opaque link token and routes to:
 *  - happy path: branding header + interactive form
 *  - 410 (dead/rotated/revoked link): "no longer active"
 *  - 423 (paused/suspended), or branding that reports the lane off: paused notice
 */
export default async function CheckinPage({ params }: CheckinPageProps) {
  const { token } = await params;

  let branding: CheckinBrandingData;
  try {
    const res = await checkinApi.getBranding(token);
    branding = res.data;
  } catch (err) {
    if (isApiError(err) && err.status === 410) return <DeadLinkNotice />;
    if (isApiError(err) && err.status === 423) return <StorePausedNotice />;
    return <GenericError />;
  }

  if (!branding.checkin_enabled || branding.checkin_paused) {
    return <StorePausedNotice branding={branding} />;
  }

  return (
    <>
      <BrandingHeader branding={branding} />
      <main className="flex-1 px-6 py-6">
        <CheckinForm token={token} branding={branding} />
      </main>
    </>
  );
}
