/**
 * Schedule one-way route search page.
 *
 * Parses route direction params from URL, renders search page with SEO.
 * URL: /{lang}/schedule/route/{dep}-{arr}-{dateFrom}-{dateTo}[-{timeRange}][-C{conn}]
 */

import { lazy, Suspense } from "react";
import { useParams, Navigate } from "@modern-js/runtime/router";
import { useTranslation } from "@/i18n/provider.js";
import { parseScheduleRouteParams } from "@/features/schedule/url.js";
import { buildScheduleSearchSeo } from "@/features/schedule/seo.js";
import { SeoHead } from "@/ui/seo/SeoHead.js";
import { FlightListSkeleton } from "@/ui/flights/FlightListSkeleton.js";
import { ErrorPage } from "@/ui/errors/ErrorPage.js";
import { getEnv } from "@/env/index.js";
import { useCityName } from "@/shared/hooks/useDictionaries.js";
import { scheduleDateRedirect } from "../../_guards.js";

const ScheduleSearchPage = lazy(() =>
  import("@/features/schedule/components/ScheduleSearchPage.js").then(
    (m) => ({ default: m.ScheduleSearchPage }),
  ),
);

export default function ScheduleRouteSearchPage(): JSX.Element {
  const { t } = useTranslation();
  const routeParams = useParams<{ params: string; lang: string }>();
  const raw = routeParams.params ?? "";
  const locale = routeParams.lang ?? "ru-ru";
  const parsed = parseScheduleRouteParams(raw);

  // Resolve IATA → city names so `<title>` reads
  // "Расписание по маршруту: Москва-Мурманск" instead of "MOW-MMK".
  // Hooks must run unconditionally; pass empty codes if parsing failed.
  const depName = useCityName(parsed?.departure ?? "");
  const arrName = useCityName(parsed?.arrival ?? "");

  if (!parsed) return <ErrorPage code="404" />;

  const redirect = scheduleDateRedirect(locale, parsed.dateFrom);
  if (redirect) return <Navigate to={redirect} replace />;

  const canonicalOrigin = getEnv().PROD_ORIGIN;
  const scheduleParams = { type: "route" as const, outbound: parsed };
  const seoProps = buildScheduleSearchSeo(t, scheduleParams, locale, canonicalOrigin, {
    departure: depName,
    arrival: arrName,
  });

  return (
    <>
      <SeoHead {...seoProps} />
      <Suspense fallback={<FlightListSkeleton />}>
        <ScheduleSearchPage params={scheduleParams} />
      </Suspense>
    </>
  );
}
