/**
 * Schedule flight details page component.
 *
 * Receives parsed flight IDs from catch-all route, fetches details
 * via useScheduleDetails, renders multi-leg flight info.
 * No SignalR -- schedule data is static.
 *
 * @module
 */

import type { FC } from "react";
import { useTranslation } from "@/i18n/provider.js";
import { FlightCard } from "@/ui/flights/FlightCard.js";
import { FlightListSkeleton } from "@/ui/flights/FlightListSkeleton.js";
import { SeoHead } from "@/ui/seo/SeoHead.js";
import { JsonLdRenderer } from "@/shared/seo/json-ld.js";
import { useScheduleDetails } from "../hooks/useScheduleDetails.js";
import { buildScheduleDetailsSeo } from "../seo.js";
import { buildScheduleFlightJsonLd } from "../json-ld.js";
import type { IScheduleFlightId, IFlightLeg } from "../types.js";

export interface ScheduleDetailsPageProps {
  /** Parsed flight identifiers from the catch-all URL */
  flights: IScheduleFlightId[];
  /** Current locale for SEO */
  locale: string;
  /** Canonical origin for SEO URLs */
  canonicalOrigin: string;
}

/**
 * Convert yyyyMMdd to yyyy-MM-dd for the API.
 */
function formatApiDate(yyyymmdd: string): string {
  if (yyyymmdd.length !== 8) return yyyymmdd;
  return `${yyyymmdd.slice(0, 4)}-${yyyymmdd.slice(4, 6)}-${yyyymmdd.slice(6, 8)}`;
}

/**
 * Extract legs from a flight (handles both Direct and MultiLeg).
 */
function getLegs(flight: { routeType: string; leg?: IFlightLeg; legs?: IFlightLeg[] }): IFlightLeg[] {
  if (flight.routeType === "Direct" && "leg" in flight && flight.leg) {
    return [flight.leg];
  }
  if ("legs" in flight && flight.legs) {
    return flight.legs;
  }
  return [];
}

export const ScheduleDetailsPage: FC<ScheduleDetailsPageProps> = ({
  flights: flightIds,
  locale,
  canonicalOrigin,
}) => {
  const { t } = useTranslation();

  // Build API params from flight IDs
  const detailsParams = {
    flights: flightIds.map(
      (f) => `${f.carrier}${f.flightNumber}${f.suffix ?? ""}`,
    ),
    dates: flightIds.map((f) => formatApiDate(f.date)),
    // Use first flight's inferred departure/arrival as fallback
    departure: "",
    arrival: "",
  };

  const { flights, loading, error } = useScheduleDetails(detailsParams);

  if (loading) {
    return <FlightListSkeleton count={flightIds.length} />;
  }

  if (error) {
    return (
      <div className="schedule-details schedule-details--error" data-testid="schedule-details-error">
        <p>Failed to load schedule details. Please try again.</p>
      </div>
    );
  }

  if (flights.length === 0) {
    return (
      <div className="schedule-details schedule-details--not-found" data-testid="schedule-details-not-found">
        <p>Schedule details not found.</p>
      </div>
    );
  }

  // SEO
  const seoProps = buildScheduleDetailsSeo(t, flights, locale, canonicalOrigin, flightIds);

  return (
    <div className="schedule-details" data-testid="schedule-details">
      <SeoHead {...seoProps} />

      {flights.map((flight) => {
        const jsonLd = buildScheduleFlightJsonLd(flight);
        const legs = getLegs(flight);
        const flightNumber = `${flight.flightId.carrier} ${flight.flightId.flightNumber}`;

        return (
          <div key={flight.id} className="schedule-details__flight" data-testid={`flight-${flight.id}`}>
            <JsonLdRenderer data={jsonLd} />

            <div className="schedule-details__header">
              <h2 className="schedule-details__flight-number">{flightNumber}</h2>
              <span className="schedule-details__status">{flight.status}</span>
            </div>

            <FlightCard flight={flight} />

            {legs.map((leg) => (
              <div key={leg.index} className="schedule-details__leg" data-testid={`leg-${leg.index}`}>
                <div className="schedule-details__leg-route">
                  <span>{leg.departure.scheduled.airportCode}</span>
                  <span>&rarr;</span>
                  <span>{leg.arrival.scheduled.airportCode}</span>
                </div>
                <div className="schedule-details__leg-times">
                  <span>{leg.departure.times.scheduledDeparture.localTime}</span>
                  <span> - </span>
                  <span>{leg.arrival.times.scheduledArrival.localTime}</span>
                </div>
                {leg.equipment.name && (
                  <div className="schedule-details__aircraft">
                    {leg.equipment.name}
                  </div>
                )}
              </div>
            ))}
          </div>
        );
      })}
    </div>
  );
};
