import type { FC } from "react";
import { useTranslation } from "@/i18n/provider.js";
import {
  buildAeroflotSbSearchUrl,
  formatAeroflotRouteDate,
} from "@/shared/booking/aeroflot.js";
import type { ISimpleFlight } from "../../types.js";
import "./actions.scss";

export interface BuyTicketButtonProps {
  flight: ISimpleFlight;
  /** Kept for API compatibility; the booking URL always uses the
   *  Russian locale (matches Angular's `BuyTicketLogic.getLink`). */
  locale?: string;
}

// Angular's `BuyTicketLogic.getLink` hardcodes the path segment to
// `ru-ru` (see ClientApp/.../buy-ticket.logic.ts), regardless of the
// current UI language. React used to build `${locale}-${locale}` which
// produced `ru-ru-ru-ru` for a BCP-47 input like "ru-ru" (our router
// already emits locales in BCP-47 form), making the link 404 on the
// booking tool.
function buildBuyTicketUrl(flight: ISimpleFlight): string {
  const legs = flight.routeType === "Direct" ? [flight.leg] : flight.legs;
  const firstLeg = legs[0];
  const lastLeg = legs[legs.length - 1];
  if (!firstLeg || !lastLeg) return "";
  const dep = firstLeg.departure.scheduled.airportCode;
  const arr = lastLeg.arrival.scheduled.airportCode;
  const date = formatAeroflotRouteDate(
    firstLeg.departure.times.scheduledDeparture.local ||
      firstLeg.departure.times.scheduledDeparture.utc,
  );
  return buildAeroflotSbSearchUrl({ departure: dep, arrival: arr, date });
}

export const BuyTicketButton: FC<BuyTicketButtonProps> = ({ flight }) => {
  const { t } = useTranslation();

  const handleClick = () => {
    const url = buildBuyTicketUrl(flight);
    window.open(url, "_blank", "noopener,noreferrer");
  };

  return (
    <button
      type="button"
      className="flight-action-btn flight-action-btn--orange"
      data-testid="buy-ticket-button"
      onClick={handleClick}
    >
      {t("SHARED.BUY-TICKET")}
    </button>
  );
};
