/**
 * React hook for schedule flight details page.
 *
 * Calls `getScheduleDetails` on param change, manages loading/error/data state.
 *
 * @module
 */

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

export interface UseScheduleDetailsParams {
  flights: string[];
  dates: string[];
  departure: string;
  arrival: string;
}

export interface UseScheduleDetailsResult {
  flights: ISimpleFlight[];
  loading: boolean;
  error: ApiError | null;
}

/**
 * Hook for schedule details page. Fetches multi-flight details
 * based on flight IDs and dates.
 */
export function useScheduleDetails(
  params: UseScheduleDetailsParams,
): UseScheduleDetailsResult {
  const client = useApiClient();
  const [flights, setFlights] = useState<ISimpleFlight[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<ApiError | null>(null);

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

  // Serialize array params for dependency tracking
  const flightsKey = params.flights.join(",");
  const datesKey = params.dates.join(",");

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

    getScheduleDetails(client, paramsRef.current)
      .then((response) => {
        if (!cancelled) {
          setFlights(response.data.routes);
          setLoading(false);
        }
      })
      .catch((err: ApiError) => {
        if (!cancelled) {
          setError(err);
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [client, flightsKey, datesKey, params.departure, params.arrival]);

  return { flights, loading, error };
}
