import { requireSession } from "@/lib/auth/guards";
import { getFacets } from "@/lib/search/facets";
import { parseSearchParams } from "@/lib/search/parse-params";
import { searchVehicles } from "@/lib/search/query-vehicles";
import { searchHitsToGeoCandidates } from "@/lib/geo/candidates";
import { orderByEintreffzeit } from "@/lib/geo/eintreffzeit";
import type { Coordinates } from "@/lib/geo/types";
import { SearchTabs } from "@/components/search/SearchTabs";
import { SearchBar } from "@/components/search/SearchBar";
import { StandortBar } from "@/components/search/StandortBar";
import { FilterPanel } from "@/components/search/FilterPanel";
import { ResultList } from "@/components/search/results/ResultList";
import { VehicleResultRow, type VehicleRowData } from "@/components/search/results/VehicleResultRow";
import { de } from "@/lib/i18n/de";

type SearchParamsRecord = Record<string, string | string[] | undefined>;

/** Liest lat/lng aus der URL; liefert null, wenn unvollständig/ungültig. */
function readOrigin(sp: SearchParamsRecord): Coordinates | null {
  const lat = Number(Array.isArray(sp.lat) ? sp.lat[0] : sp.lat);
  const lng = Number(Array.isArray(sp.lng) ? sp.lng[0] : sp.lng);
  if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
  if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
  return { lat, lng };
}

export default async function FahrzeugePage({
  searchParams,
}: {
  searchParams: Promise<SearchParamsRecord>;
}) {
  // Default-deny in der Tiefe (Querschnittsstandard 1): Guard als erste Zeile.
  await requireSession();

  const sp = await searchParams;
  const facets = await getFacets("vehicle");
  const params = parseSearchParams(sp, facets);
  const hits = await searchVehicles(params);

  // ETA-Sortierung NUR wenn ein Standort gesetzt ist; sonst ungeordnet (offener
  // ETA-Slot pro Zeile).
  const origin = readOrigin(sp);
  let rows: VehicleRowData[];
  if (origin) {
    const candidates = await searchHitsToGeoCandidates(origin, hits);
    const ordered = await orderByEintreffzeit(origin, candidates);
    rows = ordered.map((o) => ({
      entityTyp: o.entityTyp,
      entityId: o.entityId,
      brigadeId: o.brigadeId,
      name: o.name,
      funkrufname: o.funkrufname,
      status: o.status,
      eta: o.eta,
    }));
  } else {
    rows = hits;
  }

  return (
    <div className="flex flex-col gap-4">
      <h1 className="text-xl font-semibold text-navy">{de.nav.fahrzeuge}</h1>
      <SearchTabs />
      <SearchBar />
      <StandortBar />
      <div className="grid grid-cols-1 gap-6 md:grid-cols-[16rem_1fr]">
        <FilterPanel facets={facets} />
        <ResultList count={rows.length}>
          {rows.map((hit) => (
            <VehicleResultRow key={hit.entityId} hit={hit} />
          ))}
        </ResultList>
      </div>
    </div>
  );
}
