import { useState, useEffect, useRef, useCallback } from 'react';
import type { PriceData } from '@/types';
import { marketDataApi } from '@/services/api';

export interface UseLivePriceOptions {
  enabled?: boolean;
  pollInterval?: number; // milliseconds, default 10000 (10 seconds)
  timeframe?: string; // chart timeframe: 1min, 5min, etc.
  onUpdate?: (priceData: PriceData) => void;
  onError?: (error: Error) => void;
}

export function useLivePrice(options: UseLivePriceOptions = {}) {
  const {
    enabled = true,
    pollInterval = 10000,
    timeframe = '1min',
    onUpdate,
    onError,
  } = options;

  const [latestPrice, setLatestPrice] = useState<PriceData | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState<Error | null>(null);
  const intervalRef = useRef<number | null>(null);
  const onUpdateRef = useRef(onUpdate);
  const onErrorRef = useRef(onError);

  // Keep refs updated
  useEffect(() => {
    onUpdateRef.current = onUpdate;
    onErrorRef.current = onError;
  }, [onUpdate, onError]);

  const fetchLatestPrice = useCallback(async () => {
    try {
      const priceData = await marketDataApi.getLivePrice(timeframe);
      setLatestPrice(priceData);
      setError(null);
      setIsConnected(true);
      onUpdateRef.current?.(priceData);
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Failed to fetch live price');
      setError(error);
      setIsConnected(false);
      onErrorRef.current?.(error);
      console.error('Live price fetch error:', error);
    }
  }, [timeframe]);

  useEffect(() => {
    if (!enabled) {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
      setIsConnected(false);
      return;
    }

    // Fetch immediately on mount
    fetchLatestPrice();

    // Set up polling interval
    intervalRef.current = setInterval(fetchLatestPrice, pollInterval);

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    };
  }, [enabled, pollInterval, fetchLatestPrice]);

  const refresh = useCallback(() => {
    fetchLatestPrice();
  }, [fetchLatestPrice]);

  return {
    latestPrice,
    isConnected,
    error,
    refresh,
  };
}
