"use client";

import { ActionIcon, Alert, Container, Group } from "@mantine/core";
import { IconArrowLeft } from "@tabler/icons-react";
import { useNavigate, useSearchParams } from "react-router";
import MemberClientPage from "@/routes/members/account/_client";
import type {
  CoreMemberDetailed,
  VpAccountDetails,
} from "@/lib/features/members/types";
import type { CoreBookingUnit } from "@/lib/features/bookings/types";
import type { CoreAccountOverview } from "@/lib/features/members/query";

interface Props {
  // Omitted when reached from the standalone promo-codes route (no campaign).
  campaignId?: string;
  promoCodeId: string;
  membershipNumber: string;
  account: VpAccountDetails | null;
  contacts: CoreMemberDetailed[];
  bookings: { data: CoreBookingUnit[]; totalRows: number };
  pointsAllocated?: number | null;
  /** Member overview strip — only when the loader was allowed to fetch it. */
  overview?: CoreAccountOverview;
  canViewPoints?: boolean;
  initialError?: string;
  // Overrides for non-promo sections (e.g. Reports) so navigation stays
  // in-section instead of jumping to the promo-codes pages.
  backHref?: string;
  contactHrefBase?: string;
}

export default function MemberInPromoCodeClient({
  campaignId,
  promoCodeId,
  membershipNumber,
  account,
  contacts,
  bookings,
  pointsAllocated,
  overview,
  canViewPoints,
  initialError,
  backHref,
  contactHrefBase,
}: Props) {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  // Carry the originating section (?from=) back to the promo-code detail page.
  const fromParam = searchParams.get("from");
  const withFrom = (url: string) =>
    fromParam ? `${url}?from=${encodeURIComponent(fromParam)}` : url;
  // Promo base differs between campaign-scoped and standalone (list) contexts.
  const promoBase = campaignId
    ? `/admin/promo-code-campaigns/${campaignId}/promo-codes/${promoCodeId}`
    : `/admin/promo-codes/${promoCodeId}`;
  const resolvedBack = backHref ?? withFrom(promoBase);
  const resolvedContactBase =
    contactHrefBase ?? `${promoBase}/members/${membershipNumber}`;
  return (
    <Container fluid px={0} py="md">
      <Group px="xl" mb="sm">
        <ActionIcon variant="subtle" onClick={() => navigate(resolvedBack)}>
          <IconArrowLeft size={18} />
        </ActionIcon>
      </Group>
      {!account ? (
        <Alert color="red" mx="xl" variant="light">
          {initialError ?? `Couldn't load member #${membershipNumber}`}
        </Alert>
      ) : (
        <MemberClientPage
          account={account}
          contacts={contacts}
          bookings={bookings}
          syncTabWithUrl={false}
          contactHrefBase={resolvedContactBase}
          pointsAllocated={pointsAllocated}
          overview={overview}
          canViewPoints={Boolean(canViewPoints)}
        />
      )}
    </Container>
  );
}
