import React, { useState, useEffect, useRef } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Typography,
  TextField,
  Slider,
  Divider,
  Paper,
  IconButton,
  Tooltip,
  Switch,
  Grid,
  Select,
  MenuItem,
  FormControl,
} from '@mui/material';
import { Close, Refresh, DragIndicator, Add, Delete } from '@mui/icons-material';
import DraggablePaper from './DraggablePaper';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { useChartColors, ChartColorSettings } from '../contexts/ChartColorContext';
import { useIndicatorSettings, IndicatorSettings, CustomReferenceLine } from '../contexts/IndicatorSettingsContext';
import { useIndicatorVisibility, IndicatorVisibilitySettings, IndicatorOrder } from '../contexts/IndicatorVisibilityContext';
import { useAuth } from '../contexts/AuthContext';

interface IndicatorParamsSettingsDialogProps {
  open: boolean;
  onClose: () => void;
  selectedIndicator?: string; // 특정 보조지표만 표시 (없으면 전체 표시)
}

// 지표별 색상/굵기 설정 키 매핑
interface ColorConfig {
  label: string;
  colorKey: keyof ChartColorSettings;
  widthKey?: keyof ChartColorSettings;
}

const indicatorColorConfigs: Record<string, ColorConfig[]> = {
  candleChart: [
    { label: '상승', colorKey: 'candleRising' },
    { label: '하락', colorKey: 'candleFalling' },
  ],
  macdLine: [
    { label: 'MACD', colorKey: 'macdLine', widthKey: 'macdLineWidth' },
    { label: '시그널', colorKey: 'signalLine', widthKey: 'signalLineWidth' },
  ],
  rsi: [
    { label: 'RSI', colorKey: 'rsiColor', widthKey: 'rsiWidth' },
    { label: '신호', colorKey: 'rsiSignalColor', widthKey: 'rsiSignalWidth' },
  ],
  stochasticK: [
    { label: '%K', colorKey: 'stochasticK', widthKey: 'stochasticKWidth' },
    { label: '%D', colorKey: 'stochasticD', widthKey: 'stochasticDWidth' },
  ],
  cci: [
    { label: 'CCI', colorKey: 'cciColor', widthKey: 'cciWidth' },
    { label: '신호', colorKey: 'cciSignalColor', widthKey: 'cciSignalWidth' },
  ],
  adx: [{ label: 'ADX', colorKey: 'adxColor', widthKey: 'adxWidth' }],
  plusDi: [
    { label: '+DI', colorKey: 'plusDiColor', widthKey: 'plusDiWidth' },
    { label: '-DI', colorKey: 'minusDiColor', widthKey: 'minusDiWidth' },
  ],
  minusDi: [],
  williamsR: [{ label: 'Williams%R', colorKey: 'williamsRColor', widthKey: 'williamsRWidth' }],
  trix: [
    { label: 'TRIX', colorKey: 'trixColor', widthKey: 'trixWidth' },
    { label: '시그널', colorKey: 'trixSignalColor', widthKey: 'trixSignalWidth' },
  ],
  newPsychological: [{ label: '신심리도', colorKey: 'newPsychologicalColor', widthKey: 'newPsychologicalWidth' }],
  investPsychological: [{ label: '투자심리도', colorKey: 'investPsychologicalColor', widthKey: 'investPsychologicalWidth' }],
  bwi: [{ label: 'BWI', colorKey: 'bwiColor', widthKey: 'bwiWidth' }],
  obv: [
    { label: 'OBV', colorKey: 'obvColor', widthKey: 'obvWidth' },
    { label: '신호', colorKey: 'obvSignalColor', widthKey: 'obvSignalWidth' },
  ],
  volumeOsc: [{ label: 'VolumeOSC', colorKey: 'volumeOscColor', widthKey: 'volumeOscWidth' }],
  vr: [{ label: 'VR', colorKey: 'vrColor', widthKey: 'vrWidth' }],
  disparity: [
    { label: '초단기', colorKey: 'disparityUltraShortColor', widthKey: 'disparityUltraShortWidth' },
    { label: '단기', colorKey: 'disparityShortColor', widthKey: 'disparityShortWidth' },
    { label: '중기', colorKey: 'disparityMidColor', widthKey: 'disparityMidWidth' },
    { label: '장기', colorKey: 'disparityLongColor', widthKey: 'disparityLongWidth' },
  ],
};

// 지표별 파라미터 키 매핑
const indicatorParamKeys: Record<string, { key: string; label: string }[]> = {
  macdLine: [{ key: 'macdFastPeriod', label: '단기 EMA' }, { key: 'macdSlowPeriod', label: '장기 EMA' }, { key: 'macdSignalPeriod', label: '시그널' }],
  rsi: [{ key: 'rsiPeriod', label: '기간' }, { key: 'rsiSignalPeriod', label: '신호' }],
  stochasticK: [{ key: 'stochasticKPeriod', label: '기간' }, { key: 'stochasticSlowing', label: '%K' }, { key: 'stochasticDPeriod', label: '%D' }],
  cci: [{ key: 'cciPeriod', label: '기간' }, { key: 'cciSignalPeriod', label: '신호' }],
  adx: [{ key: 'adxPeriod', label: '기간' }],
  williamsR: [{ key: 'williamsRPeriod', label: '기간' }],
  trix: [{ key: 'trixPeriod', label: '기간' }, { key: 'trixSignalPeriod', label: '신호' }],
  newPsychological: [{ key: 'newPsychologicalPeriod', label: '기간' }],
  investPsychological: [{ key: 'investPsychologicalPeriod', label: '기간' }],
  bwi: [{ key: 'bwiPeriod', label: '기간' }],
  obv: [{ key: 'obvPeriod', label: '기간' }, { key: 'obvSignalPeriod', label: '신호' }],
  volumeOsc: [{ key: 'volumeOscShortPeriod', label: '단기' }, { key: 'volumeOscLongPeriod', label: '장기' }],
  vr: [{ key: 'vrPeriod', label: '기간' }],
  disparity: [
    { key: 'disparityUltraShortPeriod', label: '초단기' },
    { key: 'disparityShortPeriod', label: '단기' },
    { key: 'disparityMidPeriod', label: '중기' },
    { key: 'disparityLongPeriod', label: '장기' },
  ],
  plusDi: [{ key: 'dmiPeriod', label: '기간' }],
};

// 지표 ID -> 지표 타입 매핑
const indicatorIdToType: Record<string, string> = {
  candleChart: 'candle',
  volume: 'volume',
  macdLine: 'macd',
  rsi: 'rsi',
  stochasticK: 'stochastic',
  cci: 'cci',
  adx: 'adx',
  plusDi: 'dmi',
  williamsR: 'williamsR',
  trix: 'trix',
  disparity: 'disparity',
  newPsychological: 'newPsychological',
  investPsychological: 'investPsychological',
  bwi: 'bwi',
  obv: 'obv',
  volumeOsc: 'volumeOsc',
  vr: 'vr',
};

// Sortable 아이템 컴포넌트 - 테이블 행 스타일
interface SortableItemProps {
  indicator: IndicatorOrder;
  checked: boolean;
  onToggle: () => void;
  colors: ChartColorSettings;
  updateColors: (c: Partial<ChartColorSettings>) => void;
  indicatorSettings: IndicatorSettings;
  updateIndicatorSettings: (s: Partial<IndicatorSettings>) => void;
  getCustomReferenceLines: (indicatorType: string) => CustomReferenceLine[];
  addCustomReferenceLine: (indicatorType: string, line: Omit<CustomReferenceLine, 'id'>) => void;
  removeCustomReferenceLine: (indicatorType: string, lineId: string) => void;
  updateCustomReferenceLine: (indicatorType: string, lineId: string, updates: Partial<CustomReferenceLine>) => void;
  colorInputRefsRef: React.RefObject<Map<string, HTMLInputElement>>;
}

const SortableItem: React.FC<SortableItemProps> = ({
  indicator,
  checked,
  onToggle,
  colors,
  updateColors,
  indicatorSettings,
  updateIndicatorSettings,
  getCustomReferenceLines,
  addCustomReferenceLine,
  removeCustomReferenceLine,
  updateCustomReferenceLine,
  colorInputRefsRef,
}) => {
  const [expanded, setExpanded] = useState(false);
  const isDisabled = indicator.settingKey === 'volume';
  const isCandleChart = indicator.settingKey === 'candleChart';
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: indicator.id, disabled: isDisabled || isCandleChart });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  const canDrag = !isDisabled && !isCandleChart;
  const colorConfigs = indicatorColorConfigs[indicator.id] || [];
  const paramKeys = indicatorParamKeys[indicator.id] || [];
  const hasSettings = indicator.settingKey !== 'volume';
  const indicatorType = indicatorIdToType[indicator.id] || indicator.id;
  const referenceLines = getCustomReferenceLines(indicatorType);
  const primaryColor = colorConfigs[0];

  const handleAddReferenceLine = () => {
    addCustomReferenceLine(indicatorType, {
      name: '기준선',
      value: 0,
      color: '#ffeb3b',
      lineStyle: 'dashed',
    });
  };

  // 파라미터와 색상 매핑 (파라미터 인덱스에 맞는 색상 찾기)
  const getColorForParam = (paramIndex: number) => {
    if (paramIndex < colorConfigs.length) {
      return colorConfigs[paramIndex];
    }
    return null;
  };

  return (
    <Box ref={setNodeRef} style={style}>
      {/* 메인 행 */}
      <Paper
        sx={{
          mb: expanded ? 0 : 0.5,
          border: '1px solid',
          borderColor: isDragging ? 'primary.main' : checked ? 'primary.light' : 'divider',
          borderRadius: expanded ? '4px 4px 0 0' : 1,
          bgcolor: isDragging ? 'action.hover' : checked ? 'action.selected' : 'background.paper',
        }}
      >
        <Box
          sx={{
            px: 1.5,
            py: 1,
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            minHeight: 48,
          }}
        >
          {/* 드래그 핸들 */}
          {canDrag ? (
            <Box
              {...attributes}
              {...listeners}
              sx={{ cursor: 'grab', '&:active': { cursor: 'grabbing' }, display: 'flex' }}
            >
              <DragIndicator color="action" sx={{ fontSize: 18 }} />
            </Box>
          ) : (
            <Box sx={{ width: 18 }} />
          )}

          {/* 지표명 */}
          <Typography variant="body2" sx={{ minWidth: 80, fontWeight: checked ? 'bold' : 'normal', fontSize: '13px' }}>
            {indicator.label}
          </Typography>

          {/* 파라미터 + 색상 (이름표시 | 값입력 | 색상버튼) */}
          <Box sx={{ flex: 1, display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}>
            {hasSettings && paramKeys.map((param, idx) => {
              const colorCfg = getColorForParam(idx);
              return (
                <Box key={param.key} sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                  {/* 파라미터 이름 */}
                  <Typography variant="caption" sx={{ fontSize: '11px', color: 'text.secondary', minWidth: 28 }}>
                    {param.label}
                  </Typography>
                  {/* 값 입력 */}
                  <TextField
                    type="number"
                    size="small"
                    value={(indicatorSettings as any)[param.key] || ''}
                    onChange={(e) => updateIndicatorSettings({ [param.key]: Number(e.target.value) })}
                    inputProps={{ min: 1, max: 999, style: { fontSize: 11, padding: '4px 6px', textAlign: 'center' } }}
                    sx={{ width: 50, '& .MuiOutlinedInput-root': { bgcolor: 'background.default' } }}
                  />
                  {/* 색상 선택 (있는 경우만) */}
                  {colorCfg && (
                    <Box sx={{ position: 'relative' }}>
                      <Box
                        sx={{
                          width: 24,
                          height: 24,
                          borderRadius: 0.5,
                          bgcolor: colors[colorCfg.colorKey] as string,
                          border: '1px solid',
                          borderColor: 'divider',
                          cursor: 'pointer',
                        }}
                      />
                      <input
                        type="color"
                        defaultValue={colors[colorCfg.colorKey] as string || '#666666'}
                        ref={(el) => {
                          if (el && colorInputRefsRef.current) {
                            colorInputRefsRef.current.set(colorCfg.colorKey, el);
                          }
                        }}
                        onInput={(e) => {
                          // ✅ 색상 선택 중: 미리보기만 업데이트 (리렌더링 방지)
                          const target = e.target as HTMLInputElement;
                          const box = target.previousElementSibling as HTMLElement;
                          if (box) {
                            box.style.backgroundColor = target.value;
                          }
                        }}
                        style={{ position: 'absolute', top: 0, left: 0, width: 24, height: 24, opacity: 0, cursor: 'pointer' }}
                      />
                    </Box>
                  )}
                </Box>
              );
            })}
          </Box>

          {/* 선 굵기 슬라이더 + 미리보기 */}
          {hasSettings && primaryColor?.widthKey && (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, minWidth: 140 }}>
              <Slider
                value={colors[primaryColor.widthKey] as number || 1.5}
                onChange={(_, value) => updateColors({ [primaryColor.widthKey!]: value as number })}
                min={0.5}
                max={5}
                step={0.5}
                size="small"
                sx={{ width: 80 }}
              />
              <Typography variant="caption" sx={{ minWidth: 28, fontSize: '10px' }}>
                {colors[primaryColor.widthKey]}px
              </Typography>
              {/* 미리보기 */}
              <Box
                sx={{
                  width: 30,
                  height: Math.max((colors[primaryColor.widthKey] as number || 1.5) * 2, 2),
                  backgroundColor: colors[primaryColor.colorKey] as string,
                  borderRadius: 0.5,
                }}
              />
            </Box>
          )}

          {/* 우측 끝: ON/OFF 스위치 + 펼침 버튼 */}
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, ml: 'auto' }}>
            <Switch checked={checked} onChange={onToggle} disabled={isDisabled || isCandleChart} size="small" />
            {hasSettings && !isCandleChart ? (
              <IconButton size="small" onClick={() => setExpanded(!expanded)} sx={{ p: 0.25 }}>
                <Typography variant="caption" sx={{ fontSize: '10px', color: 'text.secondary' }}>
                  {expanded ? '▲' : '▼'}
                </Typography>
              </IconButton>
            ) : (
              <Box sx={{ width: 24 }} />
            )}
          </Box>
        </Box>
      </Paper>

      {/* 확장된 기준선 설정 - 테이블 스타일 */}
      {expanded && hasSettings && !isCandleChart && (
        <Paper
          sx={{
            mb: 0.5,
            p: 1.5,
            border: '1px solid',
            borderTop: 'none',
            borderColor: 'divider',
            borderRadius: '0 0 4px 4px',
            bgcolor: 'action.hover',
          }}
        >
          {/* 기준선 헤더 */}
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
            <Typography variant="caption" fontWeight="bold" color="text.secondary">
              📏 기준선
            </Typography>
            <Button size="small" startIcon={<Add sx={{ fontSize: 14 }} />} onClick={handleAddReferenceLine} sx={{ fontSize: '10px', py: 0 }}>
              추가
            </Button>
          </Box>

          {referenceLines.length > 0 ? (
            <>
              {/* 기준선 테이블 헤더 */}
              <Box sx={{ p: 0.5, mb: 0.5, bgcolor: 'primary.main', borderRadius: 0.5, opacity: 0.85 }}>
                <Grid container spacing={0.5} alignItems="center">
                  <Grid item xs={3}>
                    <Typography variant="caption" fontWeight="bold" color="white" sx={{ fontSize: '10px' }}>이름</Typography>
                  </Grid>
                  <Grid item xs={2}>
                    <Typography variant="caption" fontWeight="bold" color="white" sx={{ fontSize: '10px' }}>값</Typography>
                  </Grid>
                  <Grid item xs={2}>
                    <Typography variant="caption" fontWeight="bold" color="white" sx={{ fontSize: '10px' }}>색상</Typography>
                  </Grid>
                  <Grid item xs={3}>
                    <Typography variant="caption" fontWeight="bold" color="white" sx={{ fontSize: '10px' }}>선 종류</Typography>
                  </Grid>
                  <Grid item xs={2}>
                    <Typography variant="caption" fontWeight="bold" color="white" sx={{ fontSize: '10px' }}>삭제</Typography>
                  </Grid>
                </Grid>
              </Box>

              {/* 기준선 행 */}
              {referenceLines.map((line) => (
                <Box key={line.id} sx={{ p: 0.5, mb: 0.5, bgcolor: 'background.paper', borderRadius: 0.5, border: '1px solid', borderColor: 'divider' }}>
                  <Grid container spacing={0.5} alignItems="center">
                    <Grid item xs={3}>
                      <TextField
                        size="small"
                        fullWidth
                        value={line.name}
                        onChange={(e) => updateCustomReferenceLine(indicatorType, line.id, { name: e.target.value })}
                        inputProps={{ style: { fontSize: 10, padding: '4px 6px' } }}
                      />
                    </Grid>
                    <Grid item xs={2}>
                      <TextField
                        size="small"
                        fullWidth
                        type="number"
                        value={line.value}
                        onChange={(e) => updateCustomReferenceLine(indicatorType, line.id, { value: parseFloat(e.target.value) || 0 })}
                        inputProps={{ style: { fontSize: 10, padding: '4px 6px', textAlign: 'center' } }}
                      />
                    </Grid>
                    <Grid item xs={2}>
                      <Box sx={{ position: 'relative' }}>
                        <Box sx={{ width: 20, height: 20, borderRadius: 0.5, bgcolor: line.color, border: '1px solid', borderColor: 'divider', cursor: 'pointer' }} />
                        <input
                          type="color"
                          value={line.color}
                          onChange={(e) => updateCustomReferenceLine(indicatorType, line.id, { color: e.target.value })}
                          style={{ position: 'absolute', top: 0, left: 0, width: 20, height: 20, opacity: 0, cursor: 'pointer' }}
                        />
                      </Box>
                    </Grid>
                    <Grid item xs={3}>
                      <FormControl size="small" fullWidth>
                        <Select
                          value={line.lineStyle || 'dashed'}
                          onChange={(e) => updateCustomReferenceLine(indicatorType, line.id, { lineStyle: e.target.value as 'solid' | 'dashed' | 'dotted' })}
                          sx={{ fontSize: '10px', '& .MuiSelect-select': { py: 0.5, px: 0.5 } }}
                        >
                          <MenuItem value="solid" sx={{ fontSize: '10px' }}>실선</MenuItem>
                          <MenuItem value="dashed" sx={{ fontSize: '10px' }}>점선</MenuItem>
                          <MenuItem value="dotted" sx={{ fontSize: '10px' }}>점점선</MenuItem>
                        </Select>
                      </FormControl>
                    </Grid>
                    <Grid item xs={2}>
                      <IconButton size="small" onClick={() => removeCustomReferenceLine(indicatorType, line.id)} color="error" sx={{ p: 0.25 }}>
                        <Delete sx={{ fontSize: 16 }} />
                      </IconButton>
                    </Grid>
                  </Grid>
                </Box>
              ))}
            </>
          ) : (
            <Typography variant="caption" color="text.disabled" sx={{ display: 'block', textAlign: 'center', py: 0.5 }}>
              기준선이 없습니다
            </Typography>
          )}
        </Paper>
      )}
    </Box>
  );
};

const IndicatorParamsSettingsDialog: React.FC<IndicatorParamsSettingsDialogProps> = ({ open, onClose, selectedIndicator }) => {
  const { colors, updateColors, resetColors } = useChartColors();
  const { 
    indicatorSettings, 
    updateIndicatorSettings, 
    resetIndicatorSettings,
    getCustomReferenceLines,
    addCustomReferenceLine,
    removeCustomReferenceLine,
    updateCustomReferenceLine,
  } = useIndicatorSettings();
  const { settings, order, updateSettings, updateOrder, resetSettings, saveSettings } = useIndicatorVisibility();
  const { isAuthenticated } = useAuth();

  const [tempSettings, setTempSettings] = useState<IndicatorVisibilitySettings>(settings);
  const [tempOrder, setTempOrder] = useState<IndicatorOrder[]>(order);
  
  // ✅ 로컬 색상 및 지표 설정 상태 추가 (적용 버튼 클릭 시까지 Context 업데이트 지연)
  const [localColors, setLocalColors] = useState<Partial<ChartColorSettings>>({});
  const [localIndicatorSettings, setLocalIndicatorSettings] = useState<Partial<IndicatorSettings>>({});
  
  // ✅ 색상 input ref 추적 (리렌더링 방지를 위해)
  const colorInputRefsRef = useRef<Map<string, HTMLInputElement>>(new Map());

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  );

  useEffect(() => {
    if (open) {
      setTempSettings(settings);
      setTempOrder(order);
      // ✅ 다이얼로그 열릴 때 로컬 상태 초기화
      setLocalColors({});
      setLocalIndicatorSettings({});
    }
  }, [open, settings, order]);

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (over && active.id !== over.id) {
      setTempOrder((items) => {
        const oldIndex = items.findIndex((item) => item.id === active.id);
        const newIndex = items.findIndex((item) => item.id === over.id);
        return arrayMove(items, oldIndex, newIndex);
      });
    }
  };

  const handleToggle = (key: keyof IndicatorVisibilitySettings) => {
    if (key === 'candleChart') return;
    
    if (key === 'macdLine') {
      setTempSettings(prev => ({ ...prev, macdLine: !prev.macdLine, macdHistogram: !prev.macdLine }));
    } else if (key === 'stochasticK') {
      setTempSettings(prev => ({ ...prev, stochasticK: !prev.stochasticK, stochasticD: !prev.stochasticK, stochasticSlow: !prev.stochasticK }));
    } else if (key === 'plusDi') {
      setTempSettings(prev => ({ ...prev, plusDi: !prev.plusDi, minusDi: !prev.plusDi }));
    } else if (key === 'trix') {
      setTempSettings(prev => ({ ...prev, trix: !prev.trix, trixSignal: !prev.trix }));
    } else {
      setTempSettings(prev => ({ ...prev, [key]: !prev[key] }));
    }
  };

  const handleSave = async () => {
    console.log('💾 [handleSave] 시작 - localIndicatorSettings:', localIndicatorSettings);
    console.log('💾 [handleSave] localColors:', localColors);
    
    // ✅ 모든 색상 input의 현재 값을 읽어서 localColors에 반영
    const finalColors: Partial<ChartColorSettings> = { ...localColors };
    colorInputRefsRef.current.forEach((input, key) => {
      if (input && input.value) {
        (finalColors as any)[key] = input.value;
      }
    });
    
    // ✅ 로컬 색상 및 지표 설정을 Context에 한 번에 반영
    if (Object.keys(finalColors).length > 0) {
      console.log('💾 [handleSave] updateColors 호출');
      updateColors(finalColors);
    }
    if (Object.keys(localIndicatorSettings).length > 0) {
      console.log('💾 [handleSave] updateIndicatorSettings 호출:', localIndicatorSettings);
      updateIndicatorSettings(localIndicatorSettings);
    } else {
      console.warn('⚠️ [handleSave] localIndicatorSettings 비어있음 - 스킵');
    }
    
    updateSettings(tempSettings);
    updateOrder(tempOrder);
    await saveSettings(isAuthenticated);
    onClose();
  };

  const handleReset = () => {
    if (window.confirm('모든 보조지표 설정을 초기화하시겠습니까?')) {
      resetSettings();
      resetColors();
      resetIndicatorSettings();
      // ✅ 로컬 상태도 초기화
      setLocalColors({});
      setLocalIndicatorSettings({});
      onClose();
    }
  };

  // ✅ 로컬 색상과 설정을 업데이트하는 함수 (적용 버튼 클릭 시까지 Context 업데이트 지연)
  const handleLocalColorUpdate = (updates: Partial<ChartColorSettings>) => {
    setLocalColors(prev => ({ ...prev, ...updates }));
  };

  const handleLocalSettingsUpdate = (updates: Partial<IndicatorSettings>) => {
    console.log('🔧 [handleLocalSettingsUpdate] 호출:', updates);
    setLocalIndicatorSettings(prev => {
      const updated = { ...prev, ...updates };
      console.log('🔧 [handleLocalSettingsUpdate] 업데이트 후:', updated);
      return updated;
    });
  };

  // ✅ 현재 색상 및 설정 (로컬 변경사항 반영)
  const currentColors = { ...colors, ...localColors };
  const currentIndicatorSettings = { ...indicatorSettings, ...localIndicatorSettings };

  let filteredOrder = tempOrder.filter(item => 
    item.settingKey !== 'stochasticD' &&
    item.settingKey !== 'stochasticSlow' &&
    item.settingKey !== 'trixSignal' &&
    item.settingKey !== 'minusDi' &&
    item.settingKey !== 'macdHistogram'
  );

  // 특정 보조지표만 표시하는 경우 필터링
  if (selectedIndicator) {
    filteredOrder = filteredOrder.filter(item => item.id === selectedIndicator);
  }

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      hideBackdrop={true}
      disableScrollLock={true}
      PaperComponent={DraggablePaper}
      sx={{
        pointerEvents: 'none',
        '& .MuiDialog-container': {
          pointerEvents: 'none',
          alignItems: 'flex-start',
        },
      }}
      PaperProps={{
        sx: {
          height: '85vh',
          maxHeight: 850,
          width: 700,
          pointerEvents: 'auto',
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
          border: '2px solid rgba(80, 100, 160, 0.5)',
        },
      }}
    >
      <DialogTitle sx={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        bgcolor: '#1976d2',
        color: '#fff',
        py: 1.2,
      }}>
        <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '16px', color: '#fff' }}>
          📊 {selectedIndicator 
            ? `${filteredOrder[0]?.label || '보조지표'} 설정` 
            : '보조지표 설정'}
        </Typography>
        <Box>
          <Tooltip title="초기화">
            <IconButton onClick={handleReset} size="small" sx={{ mr: 1, color: '#fff' }}>
              <Refresh />
            </IconButton>
          </Tooltip>
          <IconButton onClick={onClose} size="small" sx={{ color: '#fff' }}>
            <Close />
          </IconButton>
        </Box>
      </DialogTitle>

      <Divider />

      <DialogContent sx={{ pt: 2, overflow: 'auto' }}>
        <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1.5 }}>
          지표를 드래그하여 순서를 변경하고, ▼를 클릭하여 기준선을 설정할 수 있습니다.
        </Typography>

        {/* 드래그 가능한 목록 */}
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
          <SortableContext items={filteredOrder.map(item => item.id)} strategy={verticalListSortingStrategy}>
            {filteredOrder.map((indicator) => {
              const value = tempSettings[indicator.settingKey];
              const isChecked = typeof value === 'boolean' ? value : false;

              return (
                <SortableItem
                  key={indicator.id}
                  indicator={indicator}
                  checked={isChecked}
                  onToggle={() => handleToggle(indicator.settingKey)}
                  colors={currentColors}
                  updateColors={handleLocalColorUpdate}
                  indicatorSettings={currentIndicatorSettings}
                  updateIndicatorSettings={handleLocalSettingsUpdate}
                  getCustomReferenceLines={getCustomReferenceLines}
                  addCustomReferenceLine={addCustomReferenceLine}
                  removeCustomReferenceLine={removeCustomReferenceLine}
                  updateCustomReferenceLine={updateCustomReferenceLine}
                  colorInputRefsRef={colorInputRefsRef}
                />
              );
            })}
          </SortableContext>
        </DndContext>
      </DialogContent>

      <Divider />

      <DialogActions sx={{ p: 2 }}>
        <Button onClick={onClose} color="inherit">
          취소
        </Button>
        <Button onClick={handleSave} variant="contained" color="primary">
          적용
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default IndicatorParamsSettingsDialog;
