import Link from "next/link";
import { notFound } from "next/navigation";
import { PageHeader } from "@/components/shared/page-header";
import { CustomerDetailView } from "@/features/customers/customer-detail-view";
import { getCustomerById, getCustomerWalletAudit, walletAuditPageSize } from "@/features/customers/api";
import { customerDetailPreview } from "@/features/customers/customer-detail-mock";
import { getSessions } from "@/features/sessions/api";
import { walletActivityMock } from "@/features/customers/wallet-activity-mock";
import { CsmsApiError } from "@/lib/csms-api";
import { first, type SearchParams } from "@/lib/list-query";
import type { CustomerDetailRecord } from "@/features/customers/types";
import type { Session } from "@/features/sessions/types";
import { getServerSession } from "@/lib/auth/server-session";

export const metadata = { title: "Customer Details" };

export default async function CustomerDetailPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<SearchParams>;
}) {
  const session = await getServerSession();
  const [{ id }, query] = await Promise.all([params, searchParams]);
  if (!id) notFound();

  const previewOnly = id === "preview" && process.env.NODE_ENV !== "production";
  let customer: CustomerDetailRecord;
  if (previewOnly) {
    customer = customerDetailPreview;
  } else {
    try {
      customer = await getCustomerById(id);
    } catch (error) {
      if (error instanceof CsmsApiError && error.status === 404) notFound();
      return (
        <>
          <PageHeader title="Customer unavailable" parent={{ label: "Customers", href: "/customers" }} />
          <section role="alert" className="panel p-6">
            <h2 className="font-semibold">Unable to load customer details</h2>
            <p className="mt-2 text-sm text-muted-foreground">
              {error instanceof CsmsApiError
                ? 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>
          </section>
        </>
      );
    }
  }

  const tab = first(query.tab);
  const activeTab = tab === "activity" ? "activity" : tab === "sessions" ? "sessions" : "wallet";
  const requestedAuditPage = Number(first(query.paginate_page));
  const auditPage = Number.isSafeInteger(requestedAuditPage) && requestedAuditPage > 0
    ? requestedAuditPage
    : 1;
  let sessions: Session[] = [];
  let sessionsError: string | undefined;
  let sessionsNotice: string | undefined;
  let walletActivity = previewOnly ? walletActivityMock : [];
  let walletActivityPagination = previewOnly
    ? {
        page: 1,
        pages: 1,
        limit: walletAuditPageSize,
        start: 1,
        end: walletActivityMock.length,
        total: walletActivityMock.length,
      }
    : undefined;
  let walletActivityError: string | undefined;
  if (activeTab === "activity" && !previewOnly) {
    try {
      const result = await getCustomerWalletAudit(id, auditPage);
      walletActivity = result.entries;
      const count = result.entries.length;
      walletActivityPagination = {
        page: result.pagination.page,
        pages: Math.max(1, result.pagination.totalPages),
        limit: result.pagination.limit,
        start: count ? (result.pagination.page - 1) * result.pagination.limit + 1 : 0,
        end: count ? (result.pagination.page - 1) * result.pagination.limit + count : 0,
        total: result.pagination.totalDocs,
      };
    } catch (error) {
      walletActivityError = error instanceof CsmsApiError
        ? error.message
        : "Unable to load wallet activity. Please try again.";
    }
  }
  if (activeTab === "sessions" && !previewOnly) {
    try {
      const result = await getSessions({ user_id: id, limit: "25" });
      sessions = result.sessions;
      if (sessions.length > 10) {
        sessionsNotice = `Showing the latest 10 of ${result.totalDocs} sessions.`;
      } else if (result.hasNextPage || result.totalDocs > sessions.length) {
        sessionsNotice = `Showing ${sessions.length} of ${result.totalDocs} sessions. Open the sessions list to view more.`;
      }
    } catch {
      sessionsError = "Unable to load this customer's sessions. Please try again.";
    }
  }

  return (
    <CustomerDetailView
      customer={customer}
      previewOnly={previewOnly}
      canManage={session?.role === "admin"}
      canOpenSessions={session?.role !== "operator"}
      activeTab={activeTab}
      sessions={sessions}
      walletActivity={walletActivity}
      walletActivityPagination={walletActivityPagination}
      walletActivityError={walletActivityError}
      walletActivityPreview={previewOnly}
      sessionsError={sessionsError}
      sessionsNotice={sessionsNotice}
    />
  );
}
