/**
 * React hook for the flight details page.
 *
 * Calls `getFlightDetails` on param change, manages loading/error/data state.
 * Returns both the first flight (for primary display) and the full routes
 * array (for the mini-list sidebar).
 *
 * @module
 */

import { useState, useEffect, useRef } from "react";
import { useApiClient } from "@/shared/api/provider.js";
import { getFlightDetails } from "../api.js";
import type { FlightDetailsParams } from "../api.js";
import type { ISimpleFlight } from "../types.js";
import type { ApiError } from "@/shared/api/errors.js";

export interface UseFlightDetailsResult {
  flight: ISimpleFlight | null;
  allFlights: ISimpleFlight[];
  daysOfFlight: string[];
  loading: boolean;
  error: ApiError | null;
}

/**
 * Hook for the flight details page. Fetches the details response and exposes
 * both the first route (primary flight) and the full routes array.
 */
export function useFlightDetails(
  params: FlightDetailsParams,
): UseFlightDetailsResult {
  const client = useApiClient();
  const [allFlights, setAllFlights] = useState<ISimpleFlight[]>([]);
  const [daysOfFlight, setDaysOfFlight] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<ApiError | null>(null);

  const paramsRef = useRef(params);
  paramsRef.current = params;

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);

    getFlightDetails(client, paramsRef.current)
      .then((response) => {
        if (!cancelled) {
          setAllFlights(response.data.routes);
          setDaysOfFlight(response.data.daysOfFlight ?? []);
          setLoading(false);
        }
      })
      .catch((err: ApiError) => {
        if (!cancelled) {
          setError(err);
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [client, params.flights, params.dates]);

  return {
    flight: allFlights[0] ?? null,
    allFlights,
    daysOfFlight,
    loading,
    error,
  };
}
