/**
 * Realtime Data Context (Backend 연결)
 * - Backend의 RealtimeWebSocketHandler와 연결
 * - Python Broadcast Server 제거
 */
import React, { createContext, useContext, useState, useCallback } from 'react';
import { useRealtimeWebSocket } from '../hooks/useRealtimeWebSocket';

interface Candle {
  time: number;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
  is_closed?: boolean;
  trade_count?: number;
}

interface Indicators {
  rsi_14?: number;
  ema_9?: number;
  ema_21?: number;
  macd?: number;
  macd_signal?: number;
  macd_histogram?: number;
  bb_upper?: number;
  bb_middle?: number;
  bb_lower?: number;
  stoch_k?: number;
  stoch_d?: number;
  adx?: number;
  plus_di?: number;
  minus_di?: number;
  ma_5?: number;
  ma_10?: number;
  ma_20?: number;
  ma_60?: number;
  ma_120?: number;
  ichimoku_tenkan?: number;
  ichimoku_kijun?: number;
  ichimoku_senkou_a?: number;
  ichimoku_senkou_b?: number;
  ichimoku_chikou?: number;
}

export interface RealtimeDataContextType {
  market: string;
  timeframe: string;
  candles: Candle[];
  indicators: Indicators;
  status: 'disconnected' | 'connecting' | 'connected' | 'error';
  setMarket: (market: string) => void;
  setTimeframe: (timeframe: string) => void;
  enableRealtime: (enabled: boolean) => void;
}

export const RealtimeDataContext = createContext<RealtimeDataContextType | undefined>(undefined);

export const useRealtimeData = () => {
  const context = useContext(RealtimeDataContext);
  if (!context) {
    throw new Error('useRealtimeData must be used within RealtimeDataProvider');
  }
  return context;
};

interface RealtimeDataProviderProps {
  children: React.ReactNode;
  defaultMarket?: string;
  defaultTimeframe?: string;
}

export const RealtimeDataProvider: React.FC<RealtimeDataProviderProps> = ({
  children,
  defaultMarket = 'KRW-BTC',
  defaultTimeframe = '1m',
}) => {
  const [market, setMarketState] = useState(defaultMarket);
  const [timeframe, setTimeframeState] = useState(defaultTimeframe);
  const [enabled, setEnabled] = useState(true);

  const { status, candles, indicators } = useRealtimeWebSocket({
    market,
    timeframe,
    enabled,
    onData: (data) => {
      console.log('[RealtimeDataContext] Received data:', data.candles.length, 'candles');
    },
    onError: (error) => {
      console.error('[RealtimeDataContext] Error:', error);
    },
  });

  const setMarket = useCallback((newMarket: string) => {
    setMarketState(newMarket);
  }, []);

  const setTimeframe = useCallback((newTimeframe: string) => {
    setTimeframeState(newTimeframe);
  }, []);

  const enableRealtime = useCallback((isEnabled: boolean) => {
    setEnabled(isEnabled);
  }, []);

  const value: RealtimeDataContextType = {
    market,
    timeframe,
    candles,
    indicators,
    status,
    setMarket,
    setTimeframe,
    enableRealtime,
  };

  return (
    <RealtimeDataContext.Provider value={value}>
      {children}
    </RealtimeDataContext.Provider>
  );
};
