/**
 * React hook for flights map destination search.
 *
 * Calls `searchDestinations` on param change, manages loading/error/data state.
 * No SignalR -- map data is static.
 *
 * @module
 */

import { useState, useEffect, useCallback, useRef } from "react";
import { useApiClient } from "@/shared/api/provider.js";
import { searchDestinations } from "../api.js";
import type { FlightsMapSearchParams, IDestinationsResponse, IFlightRoute } from "../types.js";
import type { ApiError } from "@/shared/api/errors.js";

export interface UseFlightsMapSearchResult {
  routes: IFlightRoute[];
  loading: boolean;
  error: ApiError | null;
  refresh: () => void;
}

/**
 * Hook for the flights map. Fetches destination routes based on search params
 * and provides refresh capability.
 */
export function useFlightsMapSearch(
  params: FlightsMapSearchParams | null,
): UseFlightsMapSearchResult {
  const client = useApiClient();
  const [routes, setRoutes] = useState<IFlightRoute[]>([]);
  const [loading, setLoading] = useState(false);
  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(() => {
    if (!paramsRef.current) {
      setRoutes([]);
      setLoading(false);
      return;
    }

    let cancelled = false;
    setLoading(true);
    setError(null);

    searchDestinations(client, paramsRef.current)
      .then((response: IDestinationsResponse) => {
        if (!cancelled) {
          setRoutes(response.data.routes);
          setLoading(false);
        }
      })
      .catch((err: ApiError) => {
        if (!cancelled) {
          setError(err);
          setRoutes([]);
          setLoading(false);
        }
      });

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

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