import { useEffect, useRef } 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;
}

export function useTicker(symbol: string) {
  const { setTicker } = useMarketStore();
  const symbolRef = useRef(symbol);

  // Update ref when symbol changes
  useEffect(() => {
    symbolRef.current = symbol;
  }, [symbol]);

  const { subscribe, unsubscribe, isConnected } = useWebSocket({
    url: getWsUrl(),
    onMessage: (data: unknown) => {
      const msg = data as TickerMessage;
      if (msg.type === "ticker" && msg.data.symbol === symbolRef.current) {
        setTicker(msg.data);
      }
    },
  });

  // Subscribe to ticker channel when connected
  useEffect(() => {
    if (!isConnected || !symbol) return;

    const channel = `ticker:${symbol}`;
    subscribe(channel);

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

  const ticker = useMarketStore((state) => state.tickers[symbol]);

  return {
    ticker,
    isConnected,
  };
}
