import { DraftLocationDetail } from "@/features/locations/draft-detail";
import { querySessions } from "@/features/sessions/query";
import { queryChargepoints } from "@/features/chargepoints/query";
import { notFound } from "next/navigation";
import { PageHeader } from "@/components/shared/page-header";
import { LocationDetail } from "@/features/locations/location-detail";
import {
  getCurrentSiteManagerLocationIds,
  getLocation,
  getLocationChargepoints,
  getLocationSiteManagers,
  getLocationSessions,
  LocationApiError,
} from "@/features/locations/api";
import type { LocationSiteManagerAccount } from "@/features/locations/related-api-contract";
import { isCsmsApiConfigured } from "@/lib/auth/server-config";
import { getServerSession } from "@/lib/auth/server-session";
import { locations, locationAnalytics } from "@/features/locations/mock-data";
import { chargepoints } from "@/features/chargepoints/mock-data";
import { sessions } from "@/features/sessions/mock-data";
import type { LocationAnalytics } from "@/features/locations/types";
import { getOverviewToday, getOverviewHistory } from "@/features/sessions/overview-api";
import { readOverviewRange, type OverviewToday, type OverviewHistory } from "@/features/sessions/overview-contract";
import {
  first,
  readListQuery,
  paginate,
  type Pagination,
  type SearchParams,
} from "@/lib/list-query";
export const metadata = { title: "Location Details" };
export default async function Page({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<SearchParams>;
}) {
  const session = await getServerSession();
  const [{ id }, query] = await Promise.all([params, searchParams]);
  if (session?.role === "site_manager") {
    const assignedLocationIds = await getCurrentSiteManagerLocationIds();
    if (!assignedLocationIds.includes(id)) notFound();
  }
  if (id.startsWith("location-demo-"))
    return (
      <DraftLocationDetail
        analytics={locationAnalytics}
        id={id}
        tab={first(query.tab) || "overview"}
        locations={locations}
      />
    );
  let location = locations.find((row) => row.id === id);
  const apiConfigured = isCsmsApiConfigured();
  if (apiConfigured) {
    try {
      location = await getLocation(id);
    } catch (error) {
      if (error instanceof LocationApiError && error.status === 404) notFound();
      throw error;
    }
  }
  if (!location) notFound();
  const tab = ["chargepoints", "sessions", "accounts"].includes(
    first(query.tab),
  )
    ? first(query.tab)
    : "overview";
  const list = readListQuery(query);
  let locationChargepoints = chargepoints.filter((cp) => cp.locationId === id);
  let locationSessions = sessions.filter((session) => session.locationId === id);
  let analytics: LocationAnalytics | null = locationAnalytics;
  let chargepointDataComplete = true;
  let sessionDataComplete = true;
  let sessionNotice: string | undefined;
  let apiSessionPagination: Pagination | undefined;
  let siteManagers: LocationSiteManagerAccount[] | undefined;
  let siteManagerError: string | undefined;
  let overview: OverviewToday | undefined;
  let overviewHistory: OverviewHistory | undefined;
  let overviewRangeNotice: string | undefined;
  const relatedDataErrors: string[] = [];

  if (apiConfigured) {
    analytics = null;
    locationChargepoints = [];
    locationSessions = [];
  }
  if (apiConfigured && tab !== "accounts") {
    const now = new Date();
    const historyRange = readOverviewRange(query, now);
    overviewRangeNotice = historyRange.notice;
    const scope = { kind: "location" as const, id };
    const [chargepointResult, sessionResult, overviewResult, historyResult] = await Promise.allSettled([
      getLocationChargepoints(location),
      tab === "sessions" ? getLocationSessions(id, query) : Promise.resolve(undefined),
      tab === "overview" ? getOverviewToday({ scope, now }) : Promise.resolve(undefined),
      tab === "overview" ? getOverviewHistory({ scope, range: historyRange.range, period: historyRange.period }) : Promise.resolve(undefined),
    ]);
    overview = overviewResult.status === "fulfilled" ? overviewResult.value : undefined;
    overviewHistory = historyResult.status === "fulfilled" ? historyResult.value : undefined;
    if (chargepointResult.status === "fulfilled") {
      locationChargepoints = chargepointResult.value.records;
      chargepointDataComplete = chargepointResult.value.complete;
    } else {
      locationChargepoints = [];
      chargepointDataComplete = false;
      relatedDataErrors.push(
        `Chargepoints: ${
          chargepointResult.reason instanceof Error
            ? chargepointResult.reason.message
            : "Unable to load chargepoints."
        }`,
      );
    }
    if (sessionResult.status === "fulfilled" && sessionResult.value) {
      locationSessions = sessionResult.value.records;
      sessionDataComplete = sessionResult.value.complete;
      apiSessionPagination = sessionResult.value.pagination;
      sessionNotice = sessionResult.value.notice;
    } else if (sessionResult.status === "rejected") {
      locationSessions = [];
      sessionDataComplete = false;
      relatedDataErrors.push(
        `Sessions: ${
          sessionResult.reason instanceof Error
            ? sessionResult.reason.message
            : "Unable to load sessions."
        }`,
      );
    }
  }

  if (apiConfigured && tab === "accounts") {
    try {
      siteManagers = await getLocationSiteManagers(id);
    } catch (error) {
      siteManagerError = error instanceof LocationApiError
        ? [
            error.upstreamStatus ? `${error.message} (HTTP ${error.upstreamStatus})` : error.message,
            error.upstreamRequestId ? `Request ID: ${error.upstreamRequestId}` : undefined,
          ].filter(Boolean).join(" ")
        : "Unable to load Site Managers assigned to this location.";
    }
  }

  const { items: cpItems, ...cpPagination } = paginate(
    queryChargepoints(
      locationChargepoints,
      query,
    ),
    list.page,
    list.limit,
  );
  const { items: sessionItems, ...sessionPagination } = paginate(
    apiConfigured ? locationSessions : querySessions(locationSessions, query),
    list.page,
    list.limit,
  );
  return (
    <>
      <PageHeader
        title={location.name}
        parent={{ label: "Locations", href: "/locations" }}
      />
      <LocationDetail
        key={JSON.stringify(query)}
        location={location}
        analytics={analytics}
        tab={tab}
        chargepoints={
          tab === "overview"
            ? locationChargepoints
            : cpItems
        }
        sessions={apiConfigured ? locationSessions : sessionItems}
        locations={apiConfigured ? [location] : locations}
        cpPagination={cpPagination}
        sessionPagination={apiSessionPagination ?? sessionPagination}
        sessionNotice={sessionNotice}
        siteManagers={siteManagers}
        siteManagerError={siteManagerError}
        canManageSiteManagers={session?.role === "admin"}
        relatedDataErrors={relatedDataErrors}
        chargepointDataComplete={chargepointDataComplete}
        sessionDataComplete={sessionDataComplete}
        readOnlyRelatedData={apiConfigured}
        overview={overview}
        overviewHistory={overviewHistory}
        overviewRangeNotice={overviewRangeNotice}
      />
    </>
  );
}
