import { useEffect } from "react";
import { useWebSocket } from "./useWebSocket";
import { useMarketStore } from "../stores/marketStore";
import type { Ticker } from "../types/models";

const getWsUrl = () => typeof window !== 'undefined' ? (process.env.NEXT_PUBLIC_WS_URL || `ws://${window.location.hostname}:8000/ws/market`) : "ws://localhost:8000/ws/market";

interface TickerMessage {
  type: "ticker";
  data: Ticker;
}

interface TickersMessage {
  type: "tickers";
  data: Ticker[];
}

export function useAllTickers() {
  const { setTicker, setConnectionStatus } = useMarketStore();

  const { subscribe, unsubscribe, isConnected, status } = useWebSocket({
    url: getWsUrl(),
    onConnect: () => {
      setConnectionStatus(true);
    },
    onDisconnect: () => {
      setConnectionStatus(false);
    },
    onMessage: (data: unknown) => {
      const msg = data as TickerMessage | TickersMessage;

      if (msg.type === "ticker") {
        setTicker(msg.data);
      } else if (msg.type === "tickers") {
        // Batch update all tickers
        const tickers = (msg as TickersMessage).data;
        tickers.forEach((ticker) => {
          setTicker(ticker);
        });
      }
    },
  });

  // Subscribe to all tickers channel when connected
  useEffect(() => {
    if (!isConnected) return;

    const channel = "tickers";
    subscribe(channel);

    return () => {
      unsubscribe(channel);
    };
  }, [isConnected, subscribe, unsubscribe]);

  // Update connection status in store
  useEffect(() => {
    setConnectionStatus(isConnected);
  }, [isConnected, setConnectionStatus]);

  const tickers = useMarketStore((state) => state.tickers);

  return {
    tickers,
    isConnected,
    status,
  };
}
