/**
 * useChartOverlays Hook
 * Composite hook that manages all ML overlay data for trading charts
 * Combines predictions, signals, ICT concepts, and AMD zones into a single interface
 */

import { useState, useCallback, useMemo } from 'react';
import { usePredictions } from './usePredictions';
import { useSignals } from './useSignals';
import { useMlOverlayData } from './useMlOverlayData';
import type { OverlayState, OverlayConfig } from '../../modules/trading/components/charts/overlays/OverlayControlPanel';
import type { MLPrediction, SignalMarker, ICTConcept, AMDZone } from '../../types/mlOverlay.types';

// ============================================================================
// Types
// ============================================================================

export interface UseChartOverlaysOptions {
  symbol: string;
  timeframe: string;
  enabled?: boolean;
  initialOverlayState?: Partial<OverlayState>;
  initialConfig?: Partial<OverlayConfig>;
}

export interface ChartOverlayData {
  predictions: MLPrediction[];
  signals: SignalMarker[];
  ictConcepts: ICTConcept[];
  amdZones: AMDZone[];
}

export interface UseChartOverlaysResult {
  // Data
  data: ChartOverlayData;

  // State management
  overlayState: OverlayState;
  setOverlayState: (key: keyof OverlayState, value: boolean) => void;
  toggleOverlay: (key: keyof OverlayState) => void;
  enableAll: () => void;
  disableAll: () => void;

  // Configuration
  config: OverlayConfig;
  setConfig: (config: OverlayConfig) => void;
  updateConfig: (key: keyof OverlayConfig, value: string | number) => void;

  // Loading states
  isLoading: boolean;
  isPredictionsLoading: boolean;
  isSignalsLoading: boolean;
  isICTLoading: boolean;

  // Errors
  error: Error | null;

  // Actions
  refetch: () => void;
  refetchPredictions: () => void;
  refetchSignals: () => void;
  generateSignal: () => void;
  isGeneratingSignal: boolean;
}

// ============================================================================
// Default Values
// ============================================================================

const DEFAULT_OVERLAY_STATE: OverlayState = {
  predictions: true,
  signals: true,
  ictConcepts: false,
  amdZones: true,
  confidenceBands: true,
};

const DEFAULT_CONFIG: OverlayConfig = {
  predictionModel: 'ensemble',
  signalMinConfidence: 0.6,
  amdLookback: 10,
  refreshInterval: 30,
};

// ============================================================================
// Hook
// ============================================================================

export function useChartOverlays({
  symbol,
  timeframe,
  enabled = true,
  initialOverlayState = {},
  initialConfig = {},
}: UseChartOverlaysOptions): UseChartOverlaysResult {
  // State
  const [overlayState, setOverlayStateInternal] = useState<OverlayState>({
    ...DEFAULT_OVERLAY_STATE,
    ...initialOverlayState,
  });

  const [config, setConfigInternal] = useState<OverlayConfig>({
    ...DEFAULT_CONFIG,
    ...initialConfig,
  });

  // Predictions hook
  const {
    predictions,
    isLoading: isPredictionsLoading,
    error: predictionsError,
    refetch: refetchPredictions,
  } = usePredictions({
    symbol,
    timeframe,
    enabled: enabled && overlayState.predictions,
    refetchInterval: config.refreshInterval * 1000,
  });

  // Signals hook
  const {
    markers: signalMarkers,
    isLoading: isSignalsLoading,
    error: signalsError,
    refetch: refetchSignals,
    generateSignal,
    isGenerating: isGeneratingSignal,
  } = useSignals({
    symbol,
    enabled: enabled && overlayState.signals,
    refetchInterval: config.refreshInterval * 1000,
  });

  // ML Overlay data (ICT concepts and AMD zones)
  const {
    ictConcepts,
    isLoading: isICTLoading,
    error: mlError,
    refetch: refetchMl,
  } = useMlOverlayData({
    symbol,
    timeframe,
    enabled: enabled && (overlayState.ictConcepts || overlayState.amdZones),
  });

  // Combine data
  const data: ChartOverlayData = useMemo(
    () => ({
      predictions: overlayState.predictions ? predictions : [],
      signals: overlayState.signals ? (signalMarkers as SignalMarker[]) : [],
      ictConcepts: overlayState.ictConcepts ? ictConcepts : [],
      amdZones: [], // AMD zones come from ML service, add when available
    }),
    [predictions, signalMarkers, ictConcepts, overlayState]
  );

  // State setters
  const setOverlayState = useCallback(
    (key: keyof OverlayState, value: boolean) => {
      setOverlayStateInternal((prev) => ({
        ...prev,
        [key]: value,
      }));
    },
    []
  );

  const toggleOverlay = useCallback((key: keyof OverlayState) => {
    setOverlayStateInternal((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  }, []);

  const enableAll = useCallback(() => {
    setOverlayStateInternal({
      predictions: true,
      signals: true,
      ictConcepts: true,
      amdZones: true,
      confidenceBands: true,
    });
  }, []);

  const disableAll = useCallback(() => {
    setOverlayStateInternal({
      predictions: false,
      signals: false,
      ictConcepts: false,
      amdZones: false,
      confidenceBands: false,
    });
  }, []);

  // Config setters
  const setConfig = useCallback((newConfig: OverlayConfig) => {
    setConfigInternal(newConfig);
  }, []);

  const updateConfig = useCallback(
    (key: keyof OverlayConfig, value: string | number) => {
      setConfigInternal((prev) => ({
        ...prev,
        [key]: value,
      }));
    },
    []
  );

  // Refetch all data
  const refetch = useCallback(() => {
    refetchPredictions();
    refetchSignals();
    refetchMl();
  }, [refetchPredictions, refetchSignals, refetchMl]);

  // Combined loading state
  const isLoading = isPredictionsLoading || isSignalsLoading || isICTLoading;

  // Combined error
  const error = predictionsError || signalsError || mlError;

  return {
    data,
    overlayState,
    setOverlayState,
    toggleOverlay,
    enableAll,
    disableAll,
    config,
    setConfig,
    updateConfig,
    isLoading,
    isPredictionsLoading,
    isSignalsLoading,
    isICTLoading,
    error,
    refetch,
    refetchPredictions,
    refetchSignals,
    generateSignal,
    isGeneratingSignal,
  };
}

export default useChartOverlays;
