/**
 * React hook for schedule search pages.
 *
 * Calls `searchSchedule` on param change, manages loading/error/data state.
 * No SignalR -- schedule data is static.
 *
 * @module
 */

import { useState, useEffect, useCallback, useRef } from "react";
import { useApiClient } from "@/shared/api/provider.js";
import { searchSchedule } from "../api.js";
import type { IScheduleSearchRequest, IFlight } from "../types.js";
import type { ApiError } from "@/shared/api/errors.js";

export interface UseScheduleSearchResult {
  flights: IFlight[];
  loading: boolean;
  error: ApiError | null;
  refresh: () => void;
}

/**
 * Hook for schedule search pages. Fetches flights based on search params
 * and provides refresh capability.
 */
export function useScheduleSearch(
  params: IScheduleSearchRequest,
): UseScheduleSearchResult {
  const client = useApiClient();
  const [flights, setFlights] = useState<IFlight[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<ApiError | null>(null);
  const [refreshKey, setRefreshKey] = useState(0);

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

  const refresh = useCallback(() => {
    setRefreshKey((k) => k + 1);
  }, []);

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

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

    return () => {
      cancelled = true;
    };
  }, [
    client,
    params.departure,
    params.arrival,
    params.dateFrom,
    params.dateTo,
    params.timeFrom,
    params.timeTo,
    params.connections,
    refreshKey,
  ]);

  return { flights, loading, error, refresh };
}
