import { ExperimentWithDatapointRunsDto } from "@montelo/browser-client";
import { LoaderFunction, json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { withAuth } from "~/auth/withAuth";
import { ExperimentIdPage } from "~/pages/experiments/ExperimentId/ExperimentIdPage";
import { formatExperimentRunDates } from "~/pages/experiments/utils";
import { getTimezone } from "~/services/timezone.server";

type LoaderType = {
  experiment: ExperimentWithDatapointRunsDto;
  totalDatapointRuns: number;
  currentPage: number;
  totalPages: number;
  timezone: string | undefined;
};

export const loader: LoaderFunction = withAuth(async ({ request, api, params }) => {
  const experimentId = params.experimentId!;

  const { searchParams } = new URL(request.url);
  const page = parseInt(searchParams.get("page") || "1");
  const pageSize = 20;
  const skipAmount = (page - 1) * pageSize;

  const { experiment, totalDatapointRuns } =
    await api.experiment.experimentControllerGetPaginatedExperimentWithDatapointRuns({
      experimentId,
      take: pageSize.toString(),
      skip: skipAmount.toString(),
    });

  // formatting
  const timezone = await getTimezone(request);
  const formattedExperiment = formatExperimentRunDates(experiment, timezone);

  const totalPages = Math.ceil(totalDatapointRuns / pageSize);
  return json<LoaderType>({
    experiment: formattedExperiment,
    totalDatapointRuns,
    currentPage: page,
    totalPages,
    timezone,
  });
});

export default function ExperimentIdRoute() {
  const { experiment, totalDatapointRuns, currentPage, totalPages, timezone } = useLoaderData<LoaderType>();

  const formattedExperiment = timezone ? experiment : formatExperimentRunDates(experiment, timezone);
  
  return (
    <ExperimentIdPage
      experiment={formattedExperiment}
      totalDatapointRuns={totalDatapointRuns}
      currentPage={currentPage}
      totalPages={totalPages}
    />
  );
}
