import { useCallback } from "react";
import { useNavigate, useParams } from "@modern-js/runtime/router";
import type { HostContract } from "@/host-contract";
import { PopularRequestsPanel } from "@/features/popular-requests/components/PopularRequestsPanel.js";
import type { PopularRequest } from "@/features/popular-requests/types.js";

/**
 * MF expose wrapper for the Popular Requests feature.
 *
 * Renders the PopularRequestsPanel and handles navigation on click
 * by routing to the appropriate onlineboard/schedule page within the
 * host application.
 */
export interface PopularRequestsRemoteProps {
  hostContract: HostContract;
}

export default function PopularRequestsRemote({
  hostContract,
}: PopularRequestsRemoteProps): JSX.Element {
  const navigate = useNavigate();
  const params = useParams<{ lang: string }>();
  const lang = params.lang ?? hostContract.locale;

  const handleRequestClick = useCallback(
    (request: PopularRequest) => {
      const nav = hostContract.navigate ?? ((path: string) => void navigate(path));

      switch (request.mode) {
        case "FlightNumber":
          nav(`/${lang}/onlineboard`);
          return;
        case "Arrival":
          nav(`/${lang}/onlineboard`);
          return;
        case "Departure":
          nav(`/${lang}/onlineboard`);
          return;
        case "Route":
          if (request.type === "Onlineboard") {
            nav(`/${lang}/onlineboard`);
          } else {
            nav(`/${lang}/schedule`);
          }
          return;
        case "RouteWithBack":
          nav(`/${lang}/schedule`);
          return;
      }
    },
    [hostContract.navigate, navigate, lang],
  );

  return (
    <div data-mf-expose="PopularRequests">
      <PopularRequestsPanel onRequestClick={handleRequestClick} />
    </div>
  );
}
