import type { FC } from "react";
import { parseISO, format } from "date-fns";
import { useTranslation } from "@/i18n/provider.js";
import type { ISimpleFlight } from "../../types.js";
import "./actions.scss";

export interface BuyTicketButtonProps {
  flight: ISimpleFlight;
  locale: string;
}

function buildBuyTicketUrl(flight: ISimpleFlight, locale: string): string {
  const legs = flight.routeType === "Direct" ? [flight.leg] : flight.legs;
  const firstLeg = legs[0]!;
  const lastLeg = legs[legs.length - 1]!;
  const dep = firstLeg.departure.scheduled.airportCode;
  const arr = lastLeg.arrival.scheduled.airportCode;
  const depDate = parseISO(firstLeg.departure.times.scheduledDeparture.utc);
  const date = format(depDate, "yyyyMMdd");
  return `https://www.aeroflot.ru/sb/app/${locale}-${locale}#/search?adults=1&cabin=economy&children=0&infants=0&routes=${dep}.${date}.${arr}&autosearch=Y`;
}

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

  const handleClick = () => {
    const url = buildBuyTicketUrl(flight, locale);
    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>
  );
};
