import { querySessions } from "@/features/sessions/query";
import { PageHeader } from "@/components/shared/page-header";
import { sessions } from "@/features/sessions/mock-data";
import { SessionTable } from "@/features/sessions/session-table";
import {
  readListQuery,
  readPageSize,
  paginate,
  type Pagination,
  type SearchParams,
} from "@/lib/list-query";
import { getSessions } from "@/features/sessions/api";
import { sessionListState } from "@/features/sessions/list-state";
import { getLocations } from "@/features/locations/api";
import { getChargepointFilterOptions } from "@/features/chargepoints/api";
import type { SearchableFilterOption } from "@/components/shared/searchable-filter-field";
import { isCsmsApiConfigured } from "@/lib/auth/server-config";
export const metadata = { title: "Sessions" };
export default async function SessionsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>;
}) {
  const params = await searchParams;
  const source = isCsmsApiConfigured() ? "api" : "preview";
  let data = sessions;
  let pagination: Pagination | undefined;
  let loadError: string | undefined;
  let loadNotice: string | undefined;
  let locationOptions: SearchableFilterOption[] = [];
  let chargepointOptions: SearchableFilterOption[] = [];

  if (source === "api") {
    const [sessionResult, locationsResult, chargepointsResult] =
      await Promise.allSettled([
        getSessions(params),
        getLocations(),
        getChargepointFilterOptions(),
      ]);
    const filterNotices: string[] = [];

    if (sessionResult.status === "fulfilled") {
      const result = sessionResult.value;
      data = result.sessions;
      const state = sessionListState(result, params);
      pagination = state.pagination;
      loadNotice = state.notice;
    } else {
      data = [];
      loadError = "Unable to load sessions. Refresh and try again.";
    }

    pagination ??= {
      page: 1,
      pages: 1,
      limit: readPageSize(params.limit),
      total: 0,
      start: data.length ? 1 : 0,
      end: data.length,
    };

    if (locationsResult.status === "fulfilled") {
      const result = locationsResult.value;
      locationOptions = result.locations.map((location) => ({
        value: location.id,
        label: location.name,
        description: location.id,
      }));
      if (result.hasNextPage || result.totalDocs > result.locations.length) {
        filterNotices.push("Some location suggestions are not loaded; paste an ID to find them.");
      }
    } else {
      filterNotices.push("Location suggestions could not be loaded; paste a location ID in the filter.");
    }

    if (chargepointsResult.status === "fulfilled") {
      chargepointOptions = chargepointsResult.value.options;
      if (!chargepointsResult.value.complete) {
        filterNotices.push("Some chargepoint suggestions are not loaded; paste an ID to find them.");
      }
    } else {
      filterNotices.push("Chargepoint suggestions could not be loaded; paste a chargepoint ID in the filter.");
    }

    loadNotice = [loadNotice, ...filterNotices].filter(Boolean).join(" ") || undefined;
  } else {
    const query = readListQuery(params);
    const sorted = querySessions(sessions, params);
    const result = paginate(sorted, query.page, query.limit);
    data = result.items;
    pagination = {
      page: result.page,
      pages: result.pages,
      limit: result.limit,
      total: result.total,
      start: result.start,
      end: result.end,
    };
  }
  return (
    <>
      <PageHeader title="Sessions" />
      <SessionTable
        data={data}
        pagination={pagination}
        source={source}
        paginationEnabled={source === "preview"}
        loadError={loadError}
        loadNotice={loadNotice}
        locationOptions={locationOptions}
        chargepointOptions={chargepointOptions}
      />
    </>
  );
}
