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

export function useOptionsFlow({ autoRefresh = false, interval = 30000, ...filters }) {
  const [data, setData] = useState(null);
  const [filteredCount, setFilteredCount] = useState(0);
  // Check if filters are meaningful (not just empty object)
  const hasFilters = filters && Object.keys(filters).length > 0 && (filters.startDate || filters.endDate || filters.minScore || filters.minPremium || filters.session);
  const [loading, setLoading] = useState(hasFilters); // Only show loading if we have filters
  const [error, setError] = useState(null);
  const filtersRef = useRef(filters);

  // Update filters ref when filters change
  useEffect(() => {
    filtersRef.current = filters;
  }, [JSON.stringify(filters)]);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      
      // Use current filters from ref
      const currentFilters = filtersRef.current;
      const startDate = currentFilters.startDate || new Date().toISOString().split('T')[0];
      const endDate = currentFilters.endDate || startDate;
      
      const params = new URLSearchParams({
        startDate,
        endDate,
        ...Object.fromEntries(
          Object.entries(currentFilters).filter(([key]) => 
            !['startDate', 'endDate'].includes(key)
          )
        )
      });
      
      // Ensure filterNoise is passed if present
      if (currentFilters.filterNoise !== undefined) {
        params.set('filterNoise', currentFilters.filterNoise);
      }

      // Add skipPrices=true for faster initial response
      params.append('skipPrices', 'true');
      
      const response = await fetch(`${getApiUrl('/api/options/flow')}?${params}`);
      const result = await response.json();

      if (result.success) {
        setData(result.data);
        setFilteredCount(result.filtered || 0);
        setError(null);
      } else {
        throw new Error(result.error);
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, []);

  // Refetch when filters change (but only if explicitly triggered by updating activeFilters)
  useEffect(() => {
    // Only fetch if filters are meaningful (have actual filter values)
    const currentHasFilters = filters && Object.keys(filters).length > 0 && (filters.startDate || filters.endDate || filters.minScore || filters.minPremium || filters.session);
    if (currentHasFilters) {
      fetchData();
    } else {
      // If no filters, set loading to false
      setLoading(false);
    }

    if (autoRefresh && currentHasFilters) {
      const intervalId = setInterval(fetchData, interval);
      return () => clearInterval(intervalId);
    }
  }, [autoRefresh, interval, fetchData, JSON.stringify(filters)]);

  return { data, loading, error, filteredCount, refetch: fetchData };
}
