import { useState, useEffect, useCallback } from 'react';
import { getApiUrl } from '@/config/api';

/**
 * Hook to fetch stock prices and volume history for symbols
 * @param {string[]} symbols - Array of stock symbols to fetch
 * @returns {Object} { data, loading, error, refetch }
 */
export function useStockPrices(symbols) {
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchStockPrices = useCallback(async (symbolList) => {
    if (!symbolList || symbolList.length === 0) {
      setData({});
      return;
    }

    try {
      setLoading(true);
      setError(null);

      // Remove duplicates and normalize
      const uniqueSymbols = [...new Set(symbolList.map(s => s.toUpperCase().trim()))].filter(Boolean);
      
      if (uniqueSymbols.length === 0) {
        setData({});
        setLoading(false);
        return;
      }

      const params = new URLSearchParams({
        symbols: uniqueSymbols.join(',')
      });

      const response = await fetch(`${getApiUrl('/api/stock-prices')}?${params}`);
      const result = await response.json();

      if (result.success) {
        setData(result.data || {});
      } else {
        throw new Error(result.error || 'Failed to fetch stock prices');
      }
    } catch (err) {
      console.error('Error fetching stock prices:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (symbols && symbols.length > 0) {
      fetchStockPrices(symbols);
    }
  }, [symbols, fetchStockPrices]);

  return { data, loading, error, refetch: () => fetchStockPrices(symbols) };
}

