import { useState, useEffect, useRef } from "react";
import {
  getSharedConnection,
  type ConnectionStatus,
} from "../signalr/connection.js";

export interface UseLiveFlightsConfig<TParams> {
  hubUrl: string;
  channelKey: (params: TParams) => string;
}

export interface UseLiveFlightsResult<TData> {
  data: TData[];
  connectionStatus: ConnectionStatus;
}

/**
 * Generic SSR-safe hook for live flight data via SignalR.
 *
 * During SSR (`typeof window === "undefined"`), returns the initial data
 * without touching SignalR. On the client, subscribes to a SignalR channel
 * and merges incoming messages into state.
 */
export function useLiveFlights<TParams, TData>(
  params: TParams,
  initialData: TData[],
  config: UseLiveFlightsConfig<TParams>,
): UseLiveFlightsResult<TData> {
  const [data, setData] = useState<TData[]>(initialData);
  const [connectionStatus, setConnectionStatus] =
    useState<ConnectionStatus>("idle");

  // Keep a stable reference to initialData for the SSR short-circuit
  const initialDataRef = useRef(initialData);
  initialDataRef.current = initialData;

  const isClient = typeof window !== "undefined";

  useEffect(() => {
    if (!isClient) return;

    const channel = config.channelKey(params);
    const connection = getSharedConnection({ hubUrl: config.hubUrl });

    // Sync current status
    setConnectionStatus(connection.status);

    const unsubStatus = connection.onStatusChange((status) => {
      setConnectionStatus(status);
    });

    const unsubChannel = connection.subscribe(channel, (message) => {
      setData(message as TData[]);
    });

    return () => {
      unsubChannel();
      unsubStatus();
    };
  }, [isClient, config.hubUrl, config.channelKey, params]);

  if (!isClient) {
    return { data: initialData, connectionStatus: "idle" };
  }

  return { data, connectionStatus };
}
