/**
 * React hook for the online board search pages.
 *
 * Calls `searchFlights` on param change, manages loading/error/data state.
 * Thin wrapper — integration-tested by 2E/2H, not unit-tested here.
 *
 * @module
 */

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

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

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

  // Serialize params for useEffect dependency
  const paramsRef = useRef(params);
  paramsRef.current = params;

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

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

    searchFlights(client, paramsRef.current)
      .then((response) => {
        if (!cancelled) {
          setFlights(response.data?.routes ?? []);
          setLoading(false);
        }
      })
      .catch((err: unknown) => {
        console.error("[useOnlineBoard] API error:", err);
        if (!cancelled) {
          setError(err as ApiError);
          setLoading(false);
        }
      });

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

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