import BreadCrumbLink from "@/layouts/shared/page.breadcrumbLink";
import { createRoleProtectedLoader } from "@/lib/features/protectedFetcher";
import { listResorts } from "@/lib/features/resorts/query";
import type { ResortListResponse } from "@/lib/features/resorts/types";
import type { AccessScope, CoreResponse } from "@/lib/features/types";
import { FEATURE_SLUGS, getCheckedAccess, isDevInstance } from "@/lib/role-helpers";
import type { Route } from "./+types/page";
import ResortsListClientPage from "./_client";

export const handle = {
  breadcrumb: () => (
    <BreadCrumbLink links={[{ label: "Resorts" }, { label: "Overview" }]} />
  ),
};

export const loader = createRoleProtectedLoader(
  FEATURE_SLUGS.resorts,
  "read",
  async ({ request }) => {
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get("page") ?? "1", 10);
    const limit = parseInt(url.searchParams.get("pageSize") ?? "20", 10);
    const search = url.searchParams.get("search") ?? undefined;
    const grade = url.searchParams.get("grade") ?? undefined;
    const is_active = url.searchParams.get("is_active") ?? undefined;

    const cookie = request.headers.get("Cookie") ?? "";
    const [response, activeRes, inactiveRes, platRes, emerRes, titaRes, silvRes] = await Promise.all([
      listResorts(
        { page, limit, search, grade, is_active },
        { Cookie: cookie }
      ),
      listResorts({ is_active: "true", limit: 1 }, { Cookie: cookie }),
      listResorts({ is_active: "false", limit: 1 }, { Cookie: cookie }),
      listResorts({ grade: "PLATINUM", limit: 1 }, { Cookie: cookie }),
      listResorts({ grade: "EMERALD", limit: 1 }, { Cookie: cookie }),
      listResorts({ grade: "TITANIUM", limit: 1 }, { Cookie: cookie }),
      listResorts({ grade: "SILVER", limit: 1 }, { Cookie: cookie }),
    ]);

    const accessScope = getCheckedAccess(request, FEATURE_SLUGS.resorts);
    if (isDevInstance(request)) {
      accessScope.create = false;
      accessScope.update = false;
      accessScope.delete = false;
    }
    return {
      response,
      accessScope,
      metrics: {
        active: activeRes.success && activeRes.data ? activeRes.data.total : 0,
        inactive: inactiveRes.success && inactiveRes.data ? inactiveRes.data.total : 0,
        grades: {
          PLATINUM: platRes.success && platRes.data ? platRes.data.total : 0,
          EMERALD: emerRes.success && emerRes.data ? emerRes.data.total : 0,
          TITANIUM: titaRes.success && titaRes.data ? titaRes.data.total : 0,
          SILVER: silvRes.success && silvRes.data ? silvRes.data.total : 0,
        },
      },
    };
  },
);

const ResortsListPage: React.FC<Route.ComponentProps> = ({ loaderData }) => {
  const { response, accessScope, metrics } = loaderData as unknown as {
    response: CoreResponse<ResortListResponse>;
    accessScope: AccessScope;
    metrics: { active: number; inactive: number; grades: Record<string, number> };
  };

  return (
    <ResortsListClientPage
      initialData={response?.success ? response.data : { items: [], total: 0, page: 1, limit: 20 }}
      initialError={response?.success ? undefined : response?.message}
      accessScope={accessScope}
      systemMetrics={metrics}
    />
  );
};

export default ResortsListPage;
