import Link from "next/link";
import { notFound } from "next/navigation";
import { DashboardPage } from "@/components/layout/dashboard-page";
import { getDashboardRole } from "@/lib/auth/dashboard-role";
import { isMonetizationApiConfigured } from "@/lib/auth/server-config";
import { CustomerDetail } from "@/features/people/customer-detail";
import {
  CustomerApiError,
  getCustomerById,
  getCustomerWalletAudit,
} from "@/features/people/api";
import { CustomerDetailView } from "@/features/people/customer-detail-view";
import type { CustomerApiDetail } from "@/features/people/customer-api-contract";
import { PageHeader, Panel } from "@/components/shared/page";
import { first } from "@/lib/list-query";
import type { WalletAuditApiPage } from "@/features/people/wallet-audit-contract";

async function ConnectedCustomerDetail({
  id,
  walletActivityPage,
}: {
  id: string;
  walletActivityPage?: number;
}) {
  let customer: CustomerApiDetail;
  try {
    customer = await getCustomerById(id);
  } catch (error) {
    if (error instanceof CustomerApiError && error.status === 404) notFound();
    return (
      <>
        <PageHeader title="Customer unavailable" parent={{ label: "Customers", href: "/customers" }} />
        <Panel>
          <div className="p-6" role="alert">
            <h2 className="font-semibold">Unable to load customer details</h2>
            <p className="mt-2 text-sm text-muted-foreground">
              {error instanceof CustomerApiError
                ? error.message
                : "The customer service is unavailable. Please try again."}
            </p>
            <Link className="mt-4 inline-flex text-sm font-medium text-primary hover:underline" href="/customers">
              Back to customers
            </Link>
          </div>
        </Panel>
      </>
    );
  }
  let walletActivity: WalletAuditApiPage | undefined;
  let walletActivityError: string | undefined;
  if (walletActivityPage !== undefined) {
    try {
      walletActivity = await getCustomerWalletAudit(id, walletActivityPage);
    } catch (error) {
      walletActivityError = error instanceof CustomerApiError
        ? error.message
        : "Wallet activity is unavailable. Please try again.";
    }
  }
  return (
    <CustomerDetailView
      customer={{ ...customer, role: "user" }}
      source="connected"
      walletActivity={walletActivity}
      walletActivityError={walletActivityError}
    />
  );
}

export default async function DashboardRoute(props: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
  params: Promise<{ id: string }>;
}) {
  const [{ id }, query] = await Promise.all([props.params, props.searchParams]);
  const role = await getDashboardRole(
    Array.isArray(query.role) ? query.role[0] : query.role,
  );
  const requestedPage = Number(first(query.paginate_page));
  const walletActivityPage = first(query.tab) === "activity"
    ? Number.isSafeInteger(requestedPage) && requestedPage > 0
      ? requestedPage
      : 1
    : undefined;
  if (!id) notFound();
  const apiConfigured = isMonetizationApiConfigured();
  return (
    <DashboardPage role={role}>
      {apiConfigured ? (
        <ConnectedCustomerDetail
          id={id}
          walletActivityPage={walletActivityPage}
        />
      ) : (
        <CustomerDetail id={id} />
      )}
    </DashboardPage>
  );
}
