import { redirect } from "react-router";
import BreadCrumbLink from "@/layouts/shared/page.breadcrumbLink";
import { createRoleProtectedLoader } from "@/lib/features/protectedFetcher";
import { getPromoCodeByCode } from "@/lib/features/promo-codes/query";
import {
  getCampaignsForPromoCode,
  getPromoCodeAnalytics,
  getPromoCodeUsers,
} from "@/lib/features/promo-code-campaigns/query";
import type { PromoCode } from "@/lib/features/promo-codes/types";
import type {
  CampaignAnalytics,
  PromoCodeUsersResult,
} 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";
// Reuse the campaign-context rich detail page for codes opened from the list,
// even when they belong to no campaign (campaignId omitted → back returns to
// the list and per-member drill-down is disabled).
import PromoCodeRichDetail from "@/routes/promo-code-campaigns/$campaignId/promo-codes/$promoCodeId/_client";

function unwrapPromo(raw: unknown): PromoCode | null {
  if (!raw || typeof raw !== "object") return null;
  const obj = raw as Record<string, unknown>;
  if (
    "data" in obj &&
    obj.data &&
    typeof obj.data === "object" &&
    !Array.isArray(obj.data) &&
    !("name" in obj || "code" in obj || "rewards" in obj)
  ) {
    return obj.data as PromoCode;
  }
  return obj as PromoCode;
}

const EMPTY_USERS: PromoCodeUsersResult = {
  items: [],
  pagination: { page: 1, pageSize: 100, total: 0, totalPages: 1 },
};

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

export const loader = createRoleProtectedLoader(
  FEATURE_SLUGS.promoCodes,
  "read",
  async ({ request, params }) => {
    const { code } = params as { code: string };
    const cookie = { Cookie: request.headers.get("Cookie") ?? "" };
    // Preserve the incoming query (notably `?from=`) across the redirect so the
    // campaign-scoped detail page can still send Back to the originating list.
    const search = new URL(request.url).search;
    // If the code belongs to a campaign, view it in that campaign's context.
    const campaignsRes = await getCampaignsForPromoCode(code, cookie);
    if (
      campaignsRes?.success &&
      Array.isArray(campaignsRes.data) &&
      campaignsRes.data.length > 0
    ) {
      const first = campaignsRes.data[0];
      throw redirect(
        `/admin/promo-code-campaigns/${first.id}/promo-codes/${encodeURIComponent(code)}${search}`,
      );
    }
    // Not in any campaign — render the same rich detail page standalone.
    const [promoResponse, analyticsResponse, usersResponse] = await Promise.all(
      [
        getPromoCodeByCode(code, cookie),
        getPromoCodeAnalytics(code, undefined, cookie),
        getPromoCodeUsers(code, { page: 1, pageSize: 100 }, cookie),
      ],
    );
    const accessScope = getCheckedAccess(request, FEATURE_SLUGS.promoCodes);
    return {
      code,
      promoResponse,
      analyticsResponse,
      usersResponse,
      accessScope,
    };
  },
);

const Page: React.FC<Route.ComponentProps> = ({ loaderData }) => {
  const { code, promoResponse, analyticsResponse, usersResponse, accessScope } =
    loaderData as unknown as {
      code: string;
      promoResponse: CoreResponse<PromoCode>;
      analyticsResponse: CoreResponse<CampaignAnalytics>;
      usersResponse: CoreResponse<PromoCodeUsersResult>;
      accessScope: AccessScope;
    };

  return (
    <PromoCodeRichDetail
      promoCodeId={code}
      initialPromoCode={
        promoResponse?.success ? unwrapPromo(promoResponse.data) : null
      }
      initialAnalytics={
        analyticsResponse?.success ? analyticsResponse.data : null
      }
      initialUsers={usersResponse?.success ? usersResponse.data : EMPTY_USERS}
      initialError={promoResponse?.success ? undefined : promoResponse?.message}
      accessScope={accessScope}
    />
  );
};

export default Page;
