import type { FC } from "react";
import { useTranslation } from "@/i18n/provider.js";
import type { IFlightLeg } from "../../types.js";
import { StationChange } from "../FullRouteTimeline/StationChange.js";
import { detectStationChange } from "../FullRouteTimeline/detectStationChange.js";
import { TransferTime } from "./TransferTime.js";
import "./TransferBar.scss";

export interface TransferBarProps {
  leg: IFlightLeg;
  nextLeg: IFlightLeg;
  viewType: "Onlineboard" | "Schedule";
}

function arrivalLocal(leg: IFlightLeg, viewType: "Onlineboard" | "Schedule"): string {
  const t = leg.arrival.times;
  if (viewType === "Schedule") return t.scheduledArrival.local;
  return t.actualBlockOn?.local ?? t.scheduledArrival.local;
}

function departureLocal(leg: IFlightLeg, viewType: "Onlineboard" | "Schedule"): string {
  const t = leg.departure.times;
  if (viewType === "Schedule") return t.scheduledDeparture.local;
  return t.actualBlockOff?.local ?? t.scheduledDeparture.local;
}

export const TransferBar: FC<TransferBarProps> = ({ leg, nextLeg, viewType }) => {
  const { t } = useTranslation();
  const stationChange = detectStationChange(leg.arrival, nextLeg.departure);
  const separated = stationChange !== "noChange";

  const className = `transfer-bar${separated ? " transfer-bar--separated" : ""}`;

  return (
    <div className={className} data-testid="transfer-bar">
      <div className="transfer-bar__icon" aria-hidden="true">
        <svg viewBox="0 0 24 24" width="20" height="20">
          <path d="M3 12h15l-4-4m4 4-4 4" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>
      <div className="transfer-bar__content">
        <span className="transfer-bar__type">{t("SHARED.INTERMEDIATE-LANDING")}</span>
        <div className="transfer-bar__duration">
          <TransferTime
            arrivalUtc={leg.arrival.times.scheduledArrival.utc}
            departureUtc={nextLeg.departure.times.scheduledDeparture.utc}
          />
        </div>
        <div className="transfer-bar__times">
          <span>{arrivalLocal(leg, viewType)}</span>
          <span> — </span>
          <span>{departureLocal(nextLeg, viewType)}</span>
        </div>
        {separated && (
          <div className="transfer-bar__station-change">
            <StationChange from={leg.arrival} to={nextLeg.departure} />
          </div>
        )}
      </div>
    </div>
  );
};
