import { notFound } from "next/navigation";
import { PageHeader } from "@/components/shared/page-header";
import { ChargepointDetail, chargepointTabs, chargepointApiTabs } from "@/features/chargepoints/chargepoint-detail";
import { DraftChargepointDetail } from "@/features/chargepoints/draft-detail";
import {
  getChargepointDetail,
  getChargepointMessageLogs,
  getChargepointList,
  getChargepointAuthorizations,
  getChargepointAuthorizationSetting,
  getChargepointQrOrganizationCode,
} from "@/features/chargepoints/api";
import {
  authorizationUsers,
  chargepoints as previewChargepoints,
  deviceConfigurations,
} from "@/features/chargepoints/mock-data";
import { mockLogs } from "@/features/chargepoints/logs/mock-data";
import { locations as previewLocations } from "@/features/locations/mock-data";
import { getLocations } from "@/features/locations/api";
import { sessions } from "@/features/sessions/mock-data";
import { querySessions } from "@/features/sessions/query";
import { getSessions } from "@/features/sessions/api";
import { getOverviewToday } from "@/features/sessions/overview-api";
import type { OverviewToday } from "@/features/sessions/overview-contract";
import { sessionListState } from "@/features/sessions/list-state";
import { isCsmsApiConfigured } from "@/lib/auth/server-config";
import type { AuthorizationPage } from "@/features/chargepoints/authorizations/contract";
import type { NozzleStatusSummary } from "@/features/chargepoints/types";
import {
  first,
  paginate,
  readListQuery,
  readPageSize,
  type Pagination,
  type SearchParams,
} from "@/lib/list-query";

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

function isNotFoundError(error: unknown) {
  return (
    typeof error === "object" &&
    error !== null &&
    "status" in error &&
    error.status === 404
  );
}

function safeApiErrorMessage(error: unknown) {
  if (
    typeof error === "object" &&
    error !== null &&
    "name" in error &&
    error.name === "CsmsApiError" &&
    "message" in error &&
    typeof error.message === "string"
  ) {
    const upstreamStatus =
      "upstreamStatus" in error && typeof error.upstreamStatus === "number"
        ? ` (upstream HTTP ${error.upstreamStatus})`
        : "";
    return `${error.message}${upstreamStatus}`;
  }
  return "Unable to load this chargepoint. Please try again.";
}

function upstreamStatus(error: unknown) {
  return (
    typeof error === "object" &&
    error !== null &&
    "upstreamStatus" in error &&
    typeof error.upstreamStatus === "number"
  )
    ? error.upstreamStatus
    : undefined;
}

function isUpstreamServerError(error: unknown) {
  const status = upstreamStatus(error);
  return status !== undefined && status >= 500;
}

export default async function Page({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<SearchParams>;
}) {
  const [{ id }, query] = await Promise.all([params, searchParams]);
  if (id.startsWith("chargepoint-demo-")) {
    return (
      <DraftChargepointDetail
        authorizationUsers={authorizationUsers}
        deviceConfigurations={deviceConfigurations}
        id={id}
        tab={first(query.tab) || "overview"}
        locations={previewLocations}
      />
    );
  }

  const list = readListQuery(query);
  let chargepoint = previewChargepoints.find((row) => row.id === id);
  let locations = previewLocations;
  let sessionsForDetail = sessions;
  let pagination: Pagination = {
    page: 1,
    pages: 1,
    limit: 25,
    total: 0,
    start: 0,
    end: 0,
  };
  let detailLogs = chargepoint ? mockLogs(chargepoint.name) : [];
  let connectorsComplete = true;
  let nozzleSummary: NozzleStatusSummary | undefined;
  let dataWarning: string | undefined;
  let logsError: string | undefined;
  let logsNotice: string | undefined;
  let sessionsError: string | undefined;
  let sessionsNotice: string | undefined;
  let overview: OverviewToday | undefined;
  let authorizations: AuthorizationPage | undefined;
  let authorizationsError: string | undefined;
  let organizationCode: string | undefined;
  const apiConfigured = isCsmsApiConfigured();
  const requestedTab = first(query.tab) === "configuration" ? "config" : first(query.tab);

  if (apiConfigured) {
    const [detailResult, locationsResult, overviewResult, authorizationsResult, organizationCodeResult] = await Promise.allSettled([
      getChargepointDetail(id),
      getLocations(),
      getOverviewToday({ scope: { kind: "chargepoint", id } }),
      requestedTab === "authorizations" ? getChargepointAuthorizations(id, query) : Promise.resolve(undefined),
      requestedTab === "connectors" ? getChargepointQrOrganizationCode() : Promise.resolve(undefined),
    ]);
    if (authorizationsResult.status === "fulfilled") authorizations = authorizationsResult.value;
    else authorizationsError = safeApiErrorMessage(authorizationsResult.reason);
    if (organizationCodeResult.status === "fulfilled") organizationCode = organizationCodeResult.value;
    overview = overviewResult.status === "fulfilled" ? overviewResult.value : undefined;
    let apiDetail =
      detailResult.status === "fulfilled" ? detailResult.value : null;
    if (detailResult.status === "rejected") {
      if (isNotFoundError(detailResult.reason)) notFound();
      if (isUpstreamServerError(detailResult.reason)) {
        const listFallback = await getChargepointList({ chargepoint_id: id }).catch(() => null);
        const listRecord = listFallback?.chargepoints.find(
          (row) => row.id === id,
        );
        if (listFallback && listRecord) {
          apiDetail = {
            chargepoint: listRecord,
            connectorsComplete: listFallback.connectorsComplete,
            nozzleSummary: undefined,
          };
          const status = upstreamStatus(detailResult.reason);
          const statusText = status === undefined ? "" : ` (upstream HTTP ${status})`;
          dataWarning = `The chargepoint detail request failed${statusText}. Showing the record and connectors from the filtered list API.`;
        }
      }
    }
    if (!apiDetail) {
      const error = detailResult.status === "rejected" ? detailResult.reason : null;
      return (
        <>
          <PageHeader title="Chargestation unavailable" />
          <p role="alert" className="text-destructive">
            {safeApiErrorMessage(error)}
          </p>
        </>
      );
    }

    locations =
      locationsResult.status === "fulfilled"
        ? locationsResult.value.locations
        : [];
    const locationNames = new Map(
      locations.map((location) => [location.id, location.name]),
    );
    chargepoint = {
      ...apiDetail.chargepoint,
      locationName:
        locationNames.get(apiDetail.chargepoint.locationId) ??
        apiDetail.chargepoint.locationId,
    };
    if (requestedTab === "authorizations" && chargepoint.enableAuthorization === undefined) {
      try {
        const enabled = await getChargepointAuthorizationSetting({ id, name: chargepoint.name });
        chargepoint = { ...chargepoint, enableAuthorization: enabled };
      } catch {
        dataWarning = [dataWarning, "The authorization setting could not be loaded. You can still manage authorized users."].filter(Boolean).join(" ");
      }
    }
    connectorsComplete = apiDetail.connectorsComplete;
    nozzleSummary = apiDetail.nozzleSummary;
    sessionsForDetail = [];
    pagination = {
      page: 1,
      pages: 1,
      limit: readPageSize(query.limit),
      total: 0,
      start: 0,
      end: 0,
    };
    detailLogs = [];
    if (requestedTab === "sessions") {
      try {
        const sessionPage = await getSessions({ ...query, chargepoint_id: id });
        sessionsForDetail = sessionPage.sessions;
        const state = sessionListState(sessionPage, query);
        pagination = state.pagination;
        sessionsNotice = state.notice;
      } catch {
        sessionsError = "Unable to load sessions. Refresh and try again.";
      }
    }
    if (requestedTab === "logs") {
      try {
        const logPage = await getChargepointMessageLogs({
          charge_point_id: chargepoint.endpoint,
          action: first(query.log_action),
        });
        detailLogs = logPage.logs;
        if (logPage.hasNextPage || logPage.totalDocs > logPage.logs.length) {
          logsNotice = `Showing the first ${logPage.logs.length} of ${logPage.totalDocs} matching logs. The message log API does not expose server page navigation.`;
        }
      } catch (error) {
        logsError = safeApiErrorMessage(error);
      }
    }
  }

  if (!chargepoint) notFound();
  const allowedTabs = apiConfigured ? chargepointApiTabs : chargepointTabs;
  const tab = requestedTab && allowedTabs.some(item => item.id === requestedTab) ? requestedTab : "overview";
  if (!apiConfigured) {
    const { items, ...previewPagination } = paginate(
      querySessions(
        sessions.filter((session) => session.chargepointId === id),
        query,
      ),
      list.page,
      list.limit,
    );
    sessionsForDetail = items;
    pagination = previewPagination;
  }

  return (
    <>
      <PageHeader
        title={chargepoint.name}
        parent={{ label: "Chargestations", href: "/chargepoints" }}
      />
      <ChargepointDetail
        authorizationUsers={authorizationUsers}
        authorizations={authorizations}
        authorizationsError={authorizationsError}
        organizationCode={organizationCode}
        deviceConfigurations={deviceConfigurations}
        key={requestedTab === "authorizations" ? `${id}:authorizations` : JSON.stringify(query)}
        chargepoint={chargepoint}
        locations={locations}
        sessions={sessionsForDetail}
        pagination={pagination}
        tab={tab}
        logs={detailLogs}
        logsError={logsError}
        logsNotice={logsNotice}
        sessionsError={sessionsError}
        sessionsNotice={sessionsNotice}
        source={apiConfigured ? "api" : "preview"}
        connectorsComplete={connectorsComplete}
        nozzleSummary={nozzleSummary}
        dataWarning={dataWarning}
        overview={overview}
      />
    </>
  );
}
