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 { getCurrentSiteManagerLocationIds, getLocation, getLocations } from "@/features/locations/api";
import { locations as previewLocations } from "@/features/locations/mock-data";
import { LocationTable } from "@/features/locations/location-table";
import {
  readListQuery,
  first,
  paginate,
  sortRecords,
  filterRecords,
  type SearchParams,
} from "@/lib/list-query";
import { isCsmsApiConfigured } from "@/lib/auth/server-config";
import { getServerSession } from "@/lib/auth/server-session";

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

export default async function LocationsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>;
}) {
  const session = await getServerSession();
  const params = await searchParams;
  const query = readListQuery(params, "name");
  const tab = first(params.tab) === "map" ? "map" : "list";
  const source = isCsmsApiConfigured() ? "api" : "preview";
  let data = previewLocations;
  let loadError: string | undefined;
  let loadNotice: string | undefined;

  if (source === "api") {
    try {
      if (session?.role === "site_manager") {
        const assignedLocationIds = await getCurrentSiteManagerLocationIds();
        if (!assignedLocationIds.length) {
          data = [];
          loadError = "No location assignments were found for this Site Manager account.";
        } else {
          const assignedLocations = await Promise.all(
            assignedLocationIds.map((id) => getLocation(id)),
          );
          data = filterRecords(assignedLocations, query.search, {}, (row) => row.name);
        }
      } else {
        const result = await getLocations(query.search);
        const complete =
          !result.hasNextPage && result.totalDocs <= result.locations.length;
        // Some API responses ignore `name`; only match locally when all rows are present.
        data = complete
          ? filterRecords(result.locations, query.search, {}, (row) => row.name)
          : result.locations;
        if (!complete) {
          loadNotice =
            `Showing ${data.length} of ${result.totalDocs} matching locations. The location API does not expose page navigation.`;
        }
      }
    } catch {
      data = [];
      loadError = "Unable to load locations. Refresh and try again.";
    }
  }

  const filtered = sortRecords(
    source === "api"
      ? data
      : filterRecords(
          data,
          query.search,
          {},
          (row) => `${row.name} ${row.code ?? ""} ${row.address} ${row.city ?? ""}`,
        ),
    query.sort,
    query.order,
    ["name", "code", "address", "email", "phone", "latitude"],
  );
  const { items, ...pagination } = paginate(filtered, query.page, query.limit);

  return (
    <>
      <PageHeader title="Locations" />
      <QueryTabs items={[{ id: "list", label: "List" }, { id: "map", label: "Map" }]} active={tab} />
      {tab === "map" ? (
        <AssetMap
          kind="locations"
          config={getGoogleMapConfig()}
          points={filtered.map(row => ({ id: row.id, name: row.name, latitude: row.latitude, longitude: row.longitude, href: `/locations/${row.id}`, description: row.address }))}
          loadError={loadError}
          loadNotice={loadNotice}
        />
      ) : <LocationTable
        data={items}
        pagination={pagination}
        source={source}
        canManage={session?.role !== "operator"}
        searchEnabled
        paginationEnabled={source === "preview"}
        loadError={loadError}
        loadNotice={loadNotice}
      />}
    </>
  );
}
