import { LoaderFunction, defer } from "@remix-run/node";
import { Await, useLoaderData } from "@remix-run/react";
import { Suspense } from "react";
import { withAuth } from "~/auth/withAuth";
import { ExperimentIdEvalsPage } from "~/pages/experiments/ExperimentId/analytics/ExperimentIdAnalytics";
import { ExperimentIdEvalsSkeleton } from "~/pages/experiments/ExperimentId/analytics/ExperimentIdEvalsSkeleton";
import {
  DeferredExperimentIdAnalyticsLoader,
  ExperimentIdAnalyticsLoader,
} from "~/types/ExperimentIdAnalyticsLoader.types";

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

  const analyticsPromise = api.experiment.experimentControllerGetAnalyticsForExperiment({
    experimentId,
  });

  return defer<DeferredExperimentIdAnalyticsLoader>({
    analyticsPromise,
  });
});

export default function ExperimentIdEvalsRoute() {
  const { analyticsPromise } = useLoaderData<ExperimentIdAnalyticsLoader>();

  return (
    <Suspense fallback={<ExperimentIdEvalsSkeleton />}>
      <Await resolve={analyticsPromise}>
        {(analytics) => <ExperimentIdEvalsPage experiment={analytics.experiment} charts={analytics.charts} />}
      </Await>
    </Suspense>
  );
}
