import type { FC } from "react";
import { Accordion, AccordionTab } from "primereact/accordion";
import { useTranslation } from "@/i18n/provider.js";
import type { ISimpleFlight } from "../../types.js";
import { DaysOfWeekStrip } from "./DaysOfWeekStrip.js";
import { getWeekDateRange } from "./weekDateRange.js";
import "./FlightSchedule.scss";

export interface FlightScheduleProps {
  flight: ISimpleFlight;
}

function formatLocalTime(iso: string | undefined): string {
  if (!iso) return "";
  if (/^\d{2}:\d{2}$/.test(iso)) return iso;
  const match = /T(\d{2}:\d{2})/.exec(iso);
  return match ? match[1]! : iso;
}

export const FlightSchedule: FC<FlightScheduleProps> = ({ flight }) => {
  const { t } = useTranslation();

  const firstLeg = flight.routeType === "Direct" ? flight.leg : flight.legs[0];
  const lastLeg =
    flight.routeType === "Direct" ? flight.leg : flight.legs[flight.legs.length - 1];

  if (!firstLeg?.daysOfWeek?.flight) return null;
  if (!lastLeg) return null;

  const depLocal = firstLeg.departure.times.scheduledDeparture.local;
  const arrLocal = lastLeg.arrival.times.scheduledArrival.local;

  const { start, end } = getWeekDateRange(depLocal);
  const noteTemplate = t("SHARED.NOTE-TIME-SCHEDULE");
  const note = noteTemplate.replace("{START_DATE}", start).replace("{END_DATE}", end);

  return (
    <section className="flight-schedule" data-testid="flight-schedule">
      <Accordion multiple={false} activeIndex={0}>
        <AccordionTab header={t("SHARED.SCHEDULE-FLIGHT")}>
          <div className="flight-schedule__row">
            <span className="flight-schedule__label">{t("SHARED.DEPARTURE-SCHEDULED")}</span>
            <span className="flight-schedule__value">{formatLocalTime(depLocal)}</span>
          </div>
          <div className="flight-schedule__row">
            <span className="flight-schedule__label">{t("SHARED.ARRIVAL-SCHEDULED")}</span>
            <span className="flight-schedule__value">{formatLocalTime(arrLocal)}</span>
          </div>
          <div className="flight-schedule__row">
            <span className="flight-schedule__label">{t("SHARED.PATH-TIME")}</span>
            <span className="flight-schedule__value">{flight.flyingTime}</span>
          </div>
        </AccordionTab>
      </Accordion>

      <div className="flight-schedule__days-section">
        <div className="flight-schedule__section-title">
          {t("SHARED.DAYS-EXECUTE-FLIGHT")}
        </div>
        <DaysOfWeekStrip flightBitString={firstLeg.daysOfWeek.flight} />
        <div className="flight-schedule__note" data-testid="flight-schedule-note">
          {note}
        </div>
      </div>
    </section>
  );
};
