import type { FC } from "react";
import { useTranslation } from "@/i18n/provider.js";
import { operatingCarrier, type ISimpleFlight } from "../../types.js";
import { AIRLINES } from "./airlines.js";
import { buildOnlineBoardUrl } from "../../url.js";
import "./actions.scss";

export interface FlightStatusButtonProps {
  flight: ISimpleFlight;
  locale: string;
  small?: boolean;
}

export const FlightStatusButton: FC<FlightStatusButtonProps> = ({ flight, locale, small }) => {
  const { t } = useTranslation();

  const handleClick = () => {
    const carrier = operatingCarrier(flight.operatingBy);
    if (!carrier) return;
    const config = AIRLINES[carrier];
    if (!config) return;

    if (config.hasNativeStatus) {
      const path = buildOnlineBoardUrl({
        type: "details",
        carrier: flight.flightId.carrier,
        flightNumber: flight.flightId.flightNumber,
        ...(flight.flightId.suffix ? { suffix: flight.flightId.suffix } : {}),
        date: flight.flightId.date,
      });
      window.open(`/${locale}/${path}`, "_blank", "noopener,noreferrer");
    } else if (config.statusUrl) {
      window.open(config.statusUrl, "_blank", "noopener,noreferrer");
    }
  };

  const classes = [
    "flight-action-btn",
    "flight-action-btn--blue-light",
    small ? "flight-action-btn--small" : "",
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <button
      type="button"
      className={classes}
      data-testid="flight-status-button"
      title={t("SHARED.DETAILS-TOOLTIP")}
      onClick={handleClick}
    >
      {t("SHARED.DETAILS")}
    </button>
  );
};
