/**
 * 차트 섹션 컴포넌트
 * - 메인 캔들 차트
 * - 보조지표 차트들
 * - 차트 툴바 및 설정
 * 
 * React.memo로 최적화되어 props가 변경될 때만 재렌더링
 */

import React, { useRef, forwardRef, useImperativeHandle } from 'react';
import { Box, Paper } from '@mui/material';
import CandlestickChart, { ChartHandle } from '../CandlestickChart';
import IndicatorChart, { IndicatorChartHandle } from '../IndicatorChart';
import ChartToolbar, { ChartTool } from '../ChartToolbar';
import type { CandleData, IndicatorData } from '../../services/backtestApi';
import type { IndicatorVisibilitySettings } from '../../contexts/IndicatorVisibilityContext';
import type { ChartColorSettings } from '../../contexts/ChartColorContext';

export interface ChartSectionProps {
  // 데이터
  candleData: CandleData[];
  indicatorData: IndicatorData[];
  maCalculationData: CandleData[];
  
  // 설정
  symbol: string;
  timeInterval: string;
  indicatorSettings: IndicatorVisibilitySettings;
  colorSettings: ChartColorSettings;
  
  // 차트 상태
  chartMode: 'basic' | 'grid' | 'clean';
  activeTool: ChartTool | null;
  candleChartHeight: number;
  indicatorHeights: Record<string, number>;
  
  // 이벤트 핸들러
  onChartModeChange: (mode: 'basic' | 'grid' | 'clean') => void;
  onToolChange: (tool: ChartTool | null) => void;
  onHeightChange: (type: 'candle' | string, height: number) => void;
  onVisibleRangeChange?: (from: number, to: number) => void;
  
  // 선택적 props
  loading?: boolean;
  error?: string | null;
  tooltipEnabled?: boolean;
  realtimePrice?: number | null;
}

export interface ChartSectionHandle {
  chartRef: React.RefObject<ChartHandle>;
  volumeChartRef: React.RefObject<IndicatorChartHandle>;
  macdChartRef: React.RefObject<IndicatorChartHandle>;
  rsiChartRef: React.RefObject<IndicatorChartHandle>;
  stochasticChartRef: React.RefObject<IndicatorChartHandle>;
  updateLastCandle: (candle: any) => void;
  updateLastIndicators: (candle: CandleData, candles: CandleData[], indicators: IndicatorData[]) => void;
}

const ChartSection = forwardRef<ChartSectionHandle, ChartSectionProps>((props, ref) => {
  const {
    candleData,
    indicatorData,
    maCalculationData,
    symbol,
    timeInterval,
    indicatorSettings,
    colorSettings,
    chartMode,
    activeTool,
    candleChartHeight,
    indicatorHeights,
    onChartModeChange,
    onToolChange,
    onHeightChange,
    onVisibleRangeChange,
    loading = false,
    error = null,
    tooltipEnabled = false,
    realtimePrice = null,
  } = props;

  // 차트 refs
  const chartRef = useRef<ChartHandle>(null);
  const volumeChartRef = useRef<IndicatorChartHandle>(null);
  const macdChartRef = useRef<IndicatorChartHandle>(null);
  const rsiChartRef = useRef<IndicatorChartHandle>(null);
  const stochasticChartRef = useRef<IndicatorChartHandle>(null);
  const cciChartRef = useRef<IndicatorChartHandle>(null);
  const adxChartRef = useRef<IndicatorChartHandle>(null);
  const obvChartRef = useRef<IndicatorChartHandle>(null);

  // ref 노출
  useImperativeHandle(ref, () => ({
    chartRef,
    volumeChartRef,
    macdChartRef,
    rsiChartRef,
    stochasticChartRef,
    updateLastCandle: (candle: any) => {
      chartRef.current?.updateLastCandle(candle);
    },
    updateLastIndicators: (candle: CandleData, candles: CandleData[], indicators: IndicatorData[]) => {
      chartRef.current?.updateLastIndicators(candle, candles, indicators);
    },
  }));

  console.log(`🎨 [ChartSection] 렌더링: ${candleData.length}개 캔들`);

  return (
    <Box sx={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 차트 툴바 */}
      <ChartToolbar
        mode={chartMode}
        activeTool={activeTool}
        onModeChange={onChartModeChange}
        onToolChange={onToolChange}
      />

      {/* 메인 캔들 차트 */}
      <Paper
        elevation={2}
        sx={{
          mb: 1,
          overflow: 'hidden',
          bgcolor: 'background.paper',
        }}
      >
        <CandlestickChart
          ref={chartRef}
          data={candleData}
          maCalculationData={maCalculationData}
          indicatorData={indicatorData}
          height={candleChartHeight}
          colorSettings={colorSettings}
          indicatorSettings={indicatorSettings}
          onVisibleRangeChange={onVisibleRangeChange}
          showTooltip={tooltipEnabled}
        />
      </Paper>

      {/* TODO: 보조지표 차트들 - IndicatorChart props 인터페이스 수정 필요 */}

      {/* 로딩/에러 상태 */}
      {loading && (
        <Box
          sx={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            bgcolor: 'rgba(0,0,0,0.7)',
            color: 'white',
            px: 3,
            py: 2,
            borderRadius: 1,
          }}
        >
          로딩 중...
        </Box>
      )}

      {error && (
        <Box
          sx={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            bgcolor: 'error.main',
            color: 'white',
            px: 3,
            py: 2,
            borderRadius: 1,
          }}
        >
          {error}
        </Box>
      )}
    </Box>
  );
});

ChartSection.displayName = 'ChartSection';

export default React.memo(ChartSection, (prevProps, nextProps) => {
  // 얕은 비교로 최적화
  return (
    prevProps.candleData === nextProps.candleData &&
    prevProps.indicatorData === nextProps.indicatorData &&
    prevProps.chartMode === nextProps.chartMode &&
    prevProps.activeTool === nextProps.activeTool &&
    prevProps.candleChartHeight === nextProps.candleChartHeight &&
    prevProps.loading === nextProps.loading &&
    prevProps.error === nextProps.error &&
    prevProps.realtimePrice === nextProps.realtimePrice
  );
});
