import { PageHeader } from "@/components/shared/page-header";
import { QueryTabs } from "@/components/shared/query-controls";
import { AssetMap } from "@/components/shared/asset-map";
import { getGoogleMapConfig } from "@/lib/map-config";
import { chargepoints } from "@/features/chargepoints/mock-data";
import { getChargepointList } from "@/features/chargepoints/api";
import { queryChargepoints } from "@/features/chargepoints/query";
import { ChargepointTable } from "@/features/chargepoints/chargepoint-table";
import { locations as previewLocations } from "@/features/locations/mock-data";
import { getLocations } from "@/features/locations/api";
import { isCsmsApiConfigured } from "@/lib/auth/server-config";
import {
  paginate,
  first,
  readListQuery,
  type SearchParams,
} from "@/lib/list-query";

export const metadata = { title: "Chargepoint List" };

export default async function ChargepointsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>;
}) {
  const params = await searchParams;
  const query = readListQuery(params);
  const source = isCsmsApiConfigured() ? "api" : "preview";
  const tab = first(params.tab) === "map" ? "map" : "list";
  const mapsConfig = getGoogleMapConfig();
  let rows = chargepoints;
  let locations = previewLocations;
  let listComplete = true;
  let connectorsComplete = true;
  let totalDocs = 0;
  let loadError: string | undefined;
  let loadNotice: string | undefined;

  if (source === "api") {
    const [listResult, locationsResult] = await Promise.allSettled([
      getChargepointList(params),
      getLocations(),
    ]);
    locations =
      locationsResult.status === "fulfilled"
        ? locationsResult.value.locations
        : [];

    if (listResult.status === "fulfilled") {
      const result = listResult.value;
      totalDocs = result.totalDocs;
      listComplete = result.complete;
      connectorsComplete = result.connectorsComplete;
      const locationNames = new Map(
        locations.map((location) => [location.id, location.name]),
      );
      rows = result.chargepoints.map((chargepoint) => ({
        ...chargepoint,
        locationName:
          locationNames.get(chargepoint.locationId) ?? chargepoint.locationId,
      }));
      if (!listComplete) {
        loadNotice = `Showing ${rows.length} of ${result.totalDocs} chargepoints. The chargepoint API query contract does not include page navigation.`;
      }
      if (!connectorsComplete) {
        loadNotice = [
          loadNotice,
          "Connector data is incomplete or unavailable.",
        ]
          .filter(Boolean)
          .join(" ");
      }
    } else {
      rows = [];
      listComplete = false;
      connectorsComplete = false;
      loadError = "Unable to load chargepoints. Please try again.";
    }
  }

  const activeQuery = source === "api" ? {} : params;
  const filtered = source === "api"
    ? rows
    : queryChargepoints(rows, activeQuery, true);
  const paginationEnabled = source === "preview" || listComplete;
  const pageSize = paginationEnabled ? query.limit : Math.max(filtered.length, 1);
  const { items, ...pagination } = paginate(
    filtered,
    paginationEnabled ? query.page : 1,
    pageSize,
  );

  return (
    <>
      <PageHeader title="Chargestations" />
      <QueryTabs items={[{ id: "list", label: "List" }, { id: "map", label: "Map" }]} active={tab} />
      {tab === "map" ? (
        <AssetMap
          kind="chargepoints"
          config={mapsConfig}
          points={filtered.map(row => ({ id: row.id, name: row.name, latitude: row.latitude, longitude: row.longitude, href: `/chargepoints/${row.id}`, description: row.locationName, status: `${row.status} · ${row.online}` }))}
          loadError={loadError}
          loadNotice={loadNotice}
        />
      ) : <ChargepointTable
        data={items}
        pagination={{
          ...pagination,
          limit: query.limit,
          total: paginationEnabled ? pagination.total : totalDocs,
        }}
        locations={locations}
        source={source}
        readOnly={source === "api"}
        detailLinksEnabled={source === "api"}
        searchEnabled
        paginationEnabled={paginationEnabled}
        loadError={loadError}
        loadNotice={loadNotice}
        createEnabled={source === "api"}
        mapsConfig={mapsConfig}
      />}
    </>
  );
}
