import { type FC, useState } from "react";
import { useTranslation } from "@/i18n/provider.js";
import type { ISimpleFlight } from "../../types.js";
import { DaysOfWeekStrip } from "./DaysOfWeekStrip.js";
import { getWeekDateRange } from "./weekDateRange.js";
import { formatDuration, formatUtcOffset } from "@/shared/utils/datetime/index.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?.[1] ?? iso;
}

/**
 * Compute the scheduled dep→arr duration in minutes. Angular's Расписание
 * рейса shows the scheduled time, not the actual flyingTime reported by the
 * API (which reflects the real landing).
 */
function scheduledDurationMinutes(depIso: string, arrIso: string): number {
  const dep = Date.parse(depIso);
  const arr = Date.parse(arrIso);
  if (Number.isNaN(dep) || Number.isNaN(arr) || arr <= dep) return 0;
  return Math.round((arr - dep) / 60000);
}

export const FlightSchedule: FC<FlightScheduleProps> = ({ flight }) => {
  const { t } = useTranslation();
  const [collapsed, setCollapsed] = useState(false);

  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">
      <div className={`flight-schedule__accordion${collapsed ? "" : " flight-schedule__accordion--open"}`}>
        <div
          className="flight-schedule__header"
          role="button"
          tabIndex={0}
          aria-expanded={!collapsed}
          onClick={() => setCollapsed((v) => !v)}
          onKeyDown={(e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              setCollapsed((v) => !v);
            }
          }}
        >
          <span>{t("SHARED.SCHEDULE-FLIGHT")}</span>
          <span aria-hidden="true" className="flight-schedule__chevron">
            {collapsed ? "\u25BC" : "\u25B2"}
          </span>
        </div>
        {!collapsed && (
          <div className="flight-schedule__content">
            {/* Angular parity: three side-by-side columns
                (Вылет по расписанию | Прилет по расписанию | Время в пути). */}
            <div className="flight-schedule__body">
              <div className="flight-schedule__col">
                <div className="flight-schedule__label">{t("SHARED.DEPARTURE-SCHEDULED")}</div>
                <div className="flight-schedule__value">
                  {formatLocalTime(depLocal)}
                  {formatUtcOffset(depLocal) && (
                    <span className="flight-schedule__offset">
                      {formatUtcOffset(depLocal)}
                    </span>
                  )}
                </div>
              </div>
              <div className="flight-schedule__col">
                <div className="flight-schedule__label">{t("SHARED.ARRIVAL-SCHEDULED")}</div>
                <div className="flight-schedule__value">
                  {formatLocalTime(arrLocal)}
                  {formatUtcOffset(arrLocal) && (
                    <span className="flight-schedule__offset">
                      {formatUtcOffset(arrLocal)}
                    </span>
                  )}
                </div>
              </div>
              <div className="flight-schedule__col">
                <div className="flight-schedule__label">{t("SHARED.PATH-TIME")}</div>
                <div className="flight-schedule__value flight-schedule__value--duration">
                  {formatDuration(
                    scheduledDurationMinutes(depLocal, arrLocal),
                    "ru",
                  )}
                </div>
              </div>
            </div>

            <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>
          </div>
        )}
      </div>
    </section>
  );
};
