import { TraceWithLogsDto } from "@montelo/browser-client";
import { LoaderFunction, json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { withAuth } from "~/auth/withAuth";
import { TracesPage } from "~/pages/traces";
import { formatTraceDates } from "~/pages/traces/utils";
import { getTimezone } from "~/services/timezone.server";

type LoaderType = {
  traces: TraceWithLogsDto[];
  currentPage: number;
  totalPages: number;
  timezone: string | undefined;
};

export const loader: LoaderFunction = withAuth(async ({ request, api, params }) => {
  const envId = params.envId!;
  const { searchParams } = new URL(request.url);
  const page = parseInt(searchParams.get("page") || "1");
  const sortColumn = searchParams.get("sortColumn");
  const sortDirection = searchParams.get("sortDirection");
  const searchQuery = searchParams.get("q");

  const pageSize = 20;
  const skipAmount = (page - 1) * pageSize;

  const response = await api.trace.traceControllerGetTracesForEnv({
    envId,
    take: pageSize.toString(),
    skip: skipAmount.toString(),
    sortColumn: sortColumn && sortColumn !== "undefined" ? sortColumn : undefined,
    sortDirection: sortDirection && sortDirection !== "undefined" ? sortDirection : undefined,
    searchQuery: searchQuery && searchQuery !== "undefined" ? searchQuery : undefined,
  });
  const { traces, totalCount } = response;

  const timezone = await getTimezone(request);
  const formattedTraces = formatTraceDates(traces, timezone);

  return json<LoaderType>({
    traces: formattedTraces,
    currentPage: page,
    totalPages: totalCount ? Math.ceil(totalCount / pageSize) : 0,
    timezone,
  });
});

export default function TracesRoute() {
  const { traces, currentPage, totalPages, timezone } = useLoaderData<LoaderType>();

  const formattedTraces = timezone ? traces : formatTraceDates(traces, timezone);

  return <TracesPage traces={formattedTraces} currentPage={currentPage} totalPages={totalPages} />;
}
