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";
  /**
   * When true (default) the bar is labelled "Промежуточная посадка" (same
   * flight number, multi-segment). When false it is labelled "Пересадка"
   * (different flight numbers, connecting).  TZ §4.1.15.6 / §4.1.16.7.
   */
  isIntermediateLanding?: boolean;
}

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

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

/**
 * Pick the most-current UTC timestamp for transfer duration calculation.
 * TZ §4.1.15.6: "одно из актуальных на момент отображения времен расписанию,
 * ожидаемому, фактическому по каждой позиции вылет/прилет."
 */
function arrivalUtc(leg: IFlightLeg, viewType: "Onlineboard" | "Schedule"): string {
  const t = leg.arrival.times;
  if (viewType === "Schedule") return t.scheduledArrival.utc;
  return (t.actualBlockOn ?? t.estimatedBlockOn ?? t.scheduledArrival).utc;
}

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

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

  const labelKey = isIntermediateLanding
    ? "SHARED.INTERMEDIATE-LANDING-PLURAL-ONE"
    : "SHARED.FLIGHT-TRANSFER-PLURAL-ONE";

  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(labelKey)}</span>
        <div className="transfer-bar__duration">
          <TransferTime
            arrivalUtc={arrivalUtc(leg, viewType)}
            departureUtc={departureUtc(nextLeg, viewType)}
          />
        </div>
        <div className="transfer-bar__times">
          <span>{arrivalLocal(leg, viewType)}</span>
          <span> — </span>
          <span>{departureLocal(nextLeg, viewType)}</span>
        </div>
        <div className="transfer-bar__station-change">
          <StationChange from={leg.arrival} to={nextLeg.departure} />
        </div>
      </div>
    </div>
  );
};
