import BreadCrumbLink from "@/layouts/shared/page.breadcrumbLink";
import { createRoleProtectedLoader } from "@/lib/features/protectedFetcher";
import { getCampaign } from "@/lib/features/promo-code-campaigns/query";
import type {
  PromoCodeCampaign,
  PromoCodeCampaignMap,
} from "@/lib/features/promo-code-campaigns/types";
import type { AccessScope, CoreResponse } from "@/lib/features/types";
import { FEATURE_SLUGS, getCheckedAccess } from "@/lib/role-helpers";
import type { Route } from "./+types/page";
import CampaignDetailsClientPage from "./_client";
import { PromoThemeShell } from "@/routes/promo-code-campaigns/_components/PromoThemeShell";

export const handle = {
  breadcrumb: () => (
    <BreadCrumbLink
      links={[
        { label: "Promo Codes", to: "/admin/promo-codes" },
        { label: "Campaigns", to: "/admin/promo-code-campaigns" },
        { label: "Details" },
      ]}
    />
  ),
};

export const loader = createRoleProtectedLoader(
  FEATURE_SLUGS.promoCodeCampaigns,
  "read",
  async ({ request, params }) => {
    const campaignId = (params as { campaignId: string }).campaignId;
    const cookie = { Cookie: request.headers.get("Cookie") ?? "" };
    // Only the (fast) campaign data blocks navigation; analytics is fetched
    // client-side so the page renders instantly with an analytics skeleton.
    const campaignResponse = await getCampaign(campaignId, cookie);
    const accessScope = getCheckedAccess(
      request,
      FEATURE_SLUGS.promoCodeCampaigns,
    );
    return { campaignId, campaignResponse, accessScope };
  },
);

const Page: React.FC<Route.ComponentProps> = ({ loaderData }) => {
  const { campaignId, campaignResponse, accessScope } =
    loaderData as unknown as {
      campaignId: string;
      campaignResponse: CoreResponse<
        PromoCodeCampaign & { promo_codes: PromoCodeCampaignMap[] }
      >;
      accessScope: AccessScope;
    };

  const campaign = campaignResponse?.success ? campaignResponse.data : null;

  // These campaign detail routes are registered outside
  // promo-codes.layout.tsx, so the layout's theme does not reach them.
  // Mounting the shell here keeps them in step with the dashboard.
  return (
    <PromoThemeShell>
      <CampaignDetailsClientPage
        campaignId={campaignId}
        initialCampaign={campaign}
        initialAnalytics={null}
        initialError={
          campaignResponse?.success ? undefined : campaignResponse?.message
        }
        accessScope={accessScope}
      />
    </PromoThemeShell>
  );
};

export default Page;
