import type { FC, ReactNode } from "react";
import { useTranslation } from "@/i18n/provider.js";
import type { IEquipmentFull, ISeat, SeatType, IPreviousFlight } from "../../types.js";
import { buildFlightUrlParams } from "../../url.js";
import "./panels.scss";

export interface AircraftPanelProps {
  equipment: IEquipmentFull;
  /** Current locale, e.g. "ru-ru". Used to build the previous-flight link. */
  locale?: string;
  /**
   * Local ISO date-time string for the flight's scheduled departure.
   * Used to gate whether the previous-flight chip is rendered as a link
   * (§4.1.15.9: show as link when scheduled departure date > today − 2 days).
   */
  departureDateLocal?: string;
}

function seatsByType(seats: ISeat[] | undefined, type: SeatType): number {
  if (!seats) return 0;
  return seats
    .filter((s) => s.type === type)
    .reduce((acc, s) => acc + s.count, 0);
}

function totalSeats(seats: ISeat[] | undefined): number {
  if (!seats) return 0;
  return seats.reduce((acc, s) => acc + s.count, 0);
}

/**
 * Returns true when the previous-flight chip should be an interactive link.
 *
 * Angular rule (§4.1.15.9 / `shoudShowPreviosFlight`): render the chip as a
 * link when the flight's scheduled-departure *date* is strictly after
 * (today − 2 days).  For older flights the chip shows as plain text so the
 * stale cross-link doesn't navigate to a potentially retired board page.
 */
function shouldShowPreviousFlightLink(departureDateLocal: string | undefined): boolean {
  if (!departureDateLocal) return false;
  // Extract local calendar date from the ISO string ("2026-04-21T10:30:00+03:00")
  const localDateStr = departureDateLocal.slice(0, 10); // "YYYY-MM-DD"
  const scheduledDate = new Date(localDateStr);
  if (isNaN(scheduledDate.getTime())) return false;

  const now = new Date();
  const threshold = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  threshold.setDate(threshold.getDate() - 2);

  return scheduledDate > threshold;
}

/**
 * Build the absolute URL path for the previous flight's details card.
 * Output: `/{locale}/onlineboard/{carrier}{flightNumber}-{yyyyMMdd}`
 * The date used is `previousFlight.localDate` (local departure date of the
 * previous flight), matching Angular's `dateToSearchBy = new Date(prevFlight.localDate)`.
 */
function buildPreviousFlightHref(
  prev: IPreviousFlight,
  locale: string,
): string {
  // localDate may be "YYYY-MM-DD" or ISO; compact it to "yyyyMMdd".
  const compactDate = prev.localDate.slice(0, 10).replace(/-/g, "");
  const id: Parameters<typeof buildFlightUrlParams>[0] = {
    carrier: prev.carrier,
    flightNumber: prev.flightNumber,
    date: compactDate,
  };
  if (prev.suffix !== undefined) id.suffix = prev.suffix;
  const urlSegment = buildFlightUrlParams(id);
  return `/${locale}/onlineboard/${urlSegment}`;
}

/**
 * Aircraft panel — matches Angular's flight-details-airplane layout:
 * properties arranged horizontally (Название | Количество мест | Эконом |
 * Комфорт | Бизнес | Предыдущий рейс). The aircraft title/model link is
 * rendered by the wrapping accordion row caption.
 */
export const AircraftPanel: FC<AircraftPanelProps> = ({
  equipment,
  locale,
  departureDateLocal,
}) => {
  const { t } = useTranslation();
  const aircraftInfo = equipment.aircraft;
  const aircraft = aircraftInfo?.actual ?? aircraftInfo?.scheduled;
  const seats = aircraftInfo?.configuration?.seats;
  const economy = seatsByType(seats, "Economy");
  const comfort = seatsByType(seats, "Comfort");
  const business = seatsByType(seats, "Business");
  const total = totalSeats(seats);
  const previous = aircraftInfo?.previousFlight;
  const previousLabel = previous
    ? `${previous.carrier} ${previous.flightNumber}${previous.suffix ?? ""}`
    : null;

  const showLink =
    !!previous &&
    !!locale &&
    shouldShowPreviousFlightLink(departureDateLocal);

  const previousHref =
    showLink && previous && locale
      ? buildPreviousFlightHref(previous, locale)
      : null;

  const props: Array<{
    label: string;
    value: ReactNode;
    className?: string;
  }> = [];
  if (aircraft?.name) props.push({ label: t("AIRPLANE.NAME"), value: aircraft.name });
  // §4.1.15.4: tail number (registration mark, e.g. "VP-BQS") from the
  // aircraft.actual.registration field. Shown when present.
  if (aircraft?.registration) {
    props.push({ label: t("AIRPLANE.TAIL-NUMBER"), value: aircraft.registration });
  }
  if (total > 0) props.push({ label: t("AIRPLANE.SEATS-TOTAL"), value: total });
  if (economy > 0) props.push({ label: t("AIRPLANE.SEATS-ECONOMY"), value: economy });
  if (comfort > 0) props.push({ label: t("AIRPLANE.SEATS-COMFORT"), value: comfort });
  if (business > 0) props.push({ label: t("AIRPLANE.SEATS-BUSINESS"), value: business });
  if (previousLabel) {
    props.push({
      label: t("BOARD.PREVIOUS-FLIGHT"),
      value: previousHref ? (
        <a
          href={previousHref}
          target="_blank"
          rel="noreferrer"
          className="aircraft-panel__previous-link"
        >
          {previousLabel}
        </a>
      ) : (
        previousLabel
      ),
    });
  }

  return (
    <div className="aircraft-panel" data-testid="aircraft-panel">
      {props.map((p, i) => (
        <div
          key={`${p.label}-${i}`}
          className={`aircraft-panel__prop${p.className ? ` ${p.className}` : ""}`}
        >
          <div className="aircraft-panel__label">{p.label}</div>
          <div className="aircraft-panel__value">{p.value}</div>
        </div>
      ))}
    </div>
  );
};
