/**
 * Online Board start page matching the Angular `online-board-start-page`
 * component DOM structure and CSS class names.
 *
 * Uses PageLayout for the two-column layout, PageTabs in the header-left,
 * OnlineBoardFilter + SearchHistory in content-left, and the info section
 * + popular requests in the main content area.
 *
 * No API calls on load. Pure presentation that navigates to search
 * routes via the filter component.
 *
 * @module
 */

import { type FC, useCallback, useMemo } from "react";
import { useNavigate, useParams, useSearchParams } from "@modern-js/runtime/router";
import { useTranslation } from "@/i18n/provider.js";
import { PageLayout } from "@/ui/layout/PageLayout.js";
import { PageTabs } from "@/ui/layout/PageTabs.js";
import { SearchHistory } from "@/ui/layout/SearchHistory.js";
import { OnlineBoardFilter } from "./OnlineBoardFilter.js";
import { PopularRequestsPanel } from "@/features/popular-requests/components/PopularRequestsPanel.js";
import type { PopularRequest } from "@/features/popular-requests/types.js";
import "./OnlineBoardStartPage.scss";

/**
 * Build URL search params for a given popular request.
 *
 * Schedule-type requests produce params for the schedule page;
 * Onlineboard-type requests produce params for the online board filter.
 */
export function buildPopularRequestQueryParams(
  request: PopularRequest,
): URLSearchParams {
  const params = new URLSearchParams();

  switch (request.mode) {
    case "FlightNumber":
      params.set("tab", "flight");
      params.set("carrier", request.carrier);
      params.set("flight", request.flightNumber);
      break;
    case "Departure":
      params.set("tab", "route");
      params.set("departure", request.departure);
      break;
    case "Arrival":
      params.set("tab", "route");
      params.set("arrival", request.arrival);
      break;
    case "Route":
    case "RouteWithBack":
      if (request.type === "Onlineboard") {
        params.set("tab", "route");
      }
      params.set("departure", request.departure);
      params.set("arrival", request.arrival);
      if (request.mode === "RouteWithBack" && request.type === "Schedule") {
        params.set("return", "true");
      }
      break;
  }

  return params;
}

export const OnlineBoardStartPage: FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const routeParams = useParams<{ lang: string }>();
  const lang = routeParams.lang ?? "ru";
  const [searchParams] = useSearchParams();

  /** Derive initial filter props from current URL query params */
  const filterInitialProps = useMemo(() => {
    const tab = searchParams.get("tab");
    const departure = searchParams.get("departure");
    const arrival = searchParams.get("arrival");
    const carrier = searchParams.get("carrier");
    const flight = searchParams.get("flight");
    const date = searchParams.get("date");

    // No query params — use defaults
    if (!tab && !departure && !arrival && !carrier && !flight) {
      return {};
    }

    return {
      ...(tab === "flight" || tab === "route"
        ? { initialTab: tab as "flight" | "route" }
        : {}),
      ...(departure ? { initialDeparture: departure } : {}),
      ...(arrival ? { initialArrival: arrival } : {}),
      ...(date ? { initialDate: date } : {}),
      ...(carrier && flight
        ? { initialFlightNumber: `${carrier}${flight}` }
        : {}),
    };
  }, [searchParams]);

  const handlePopularRequestClick = useCallback(
    (request: PopularRequest) => {
      const params = buildPopularRequestQueryParams(request);

      // Schedule-type requests navigate to the schedule feature
      if (request.type === "Schedule") {
        navigate({
          pathname: `/${lang}/schedule`,
          search: params.toString(),
        });
        return;
      }

      // Onlineboard requests stay on this page with query params
      navigate({
        pathname: `/${lang}/onlineboard`,
        search: params.toString(),
      });
    },
    [navigate, lang],
  );

  return (
    <div className="online-board-start-page" data-testid="online-board-start">
      <PageLayout
        headerLeft={
          <PageTabs viewType="onlineboard" />
        }
        title={
          <h1 className="text--white page-title">
            {t("BOARD.TITLE")}
          </h1>
        }
        breadcrumbs={[]}
        contentLeft={
          <>
            <OnlineBoardFilter {...filterInitialProps} />
            <SearchHistory />
          </>
        }
      >
        <section className="frame">
          <h2>{t("BOARD.BOARD-START")}</h2>

          <div className="titles-container">
            <div className="title title1">
              <a>{t("BOARD.BOARD-START-TITLE1")}</a>
              <div>
                {t("BOARD.BOARD-START-TITLE1-DESCRIPTION")}
              </div>
            </div>

            <div className="title title2">
              <a>{t("BOARD.BOARD-START-TITLE2")}</a>
              <div>
                {t("BOARD.BOARD-START-TITLE2-DESCRIPTION")}
              </div>
            </div>

            <div className="title title3">
              <a>{t("BOARD.BOARD-START-TITLE3")}</a>
              <div>
                {t("BOARD.BOARD-START-TITLE3-DESCRIPTION")}
              </div>
            </div>

            <div className="title title4">
              <a>{t("BOARD.BOARD-START-TITLE4")}</a>
              <div>
                {t("BOARD.BOARD-START-TITLE4-DESCRIPTION")}
              </div>
            </div>
          </div>

          <PopularRequestsPanel onRequestClick={handlePopularRequestClick} />
        </section>
      </PageLayout>
    </div>
  );
};
