/**
 * Schedule round-trip route search page.
 *
 * Parses outbound + return route direction params from URL.
 * URL: /{lang}/schedule/route/{outboundParams}/{returnParams}
 */

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 ScheduleRoundTripSearchPage(): JSX.Element {
  const { t } = useTranslation();
  const routeParams = useParams<{ params: string; returnParams: string; lang: string }>();
  const outboundRaw = routeParams.params ?? "";
  const inboundRaw = routeParams.returnParams ?? "";
  const locale = routeParams.lang ?? "ru-ru";

  const outbound = parseScheduleRouteParams(outboundRaw);
  const inbound = parseScheduleRouteParams(inboundRaw);

  // Resolve IATA → city names for `<title>`. Hooks must run unconditionally,
  // so call with the outbound codes (which double as the SEO heading codes)
  // even when parsing failed.
  const depName = useCityName(outbound?.departure ?? "");
  const arrName = useCityName(outbound?.arrival ?? "");

  if (!outbound || !inbound) return <ErrorPage code="404" />;

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

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

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