import React, { useState, useEffect } from 'react';
import {
  Box,
  Drawer,
  Typography,
  IconButton,
  Divider,
  TextField,
  Grid,
  Button,
  Tooltip,
  Slider,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Alert,
  Snackbar,
  Switch,
  FormControlLabel,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
} from '@mui/material';
import {
  Settings as SettingsIcon,
  Close as CloseIcon,
  ExpandMore,
  RestartAlt,
  Save as SaveIcon,
  TrendingUp,
  Visibility,
  Palette,
  OpenInNew as PopupIcon,
} from '@mui/icons-material';
import {
  loadIndicatorSettings,
  saveIndicatorSettings,
  DEFAULT_INDICATOR_SETTINGS,
  IndicatorSettings,
} from './settings/IndicatorSettingsTab';
import { useIndicatorVisibility, IndicatorVisibilitySettings, MALineConfig } from '../contexts/IndicatorVisibilityContext';
import { useAuth } from '../contexts/AuthContext';
import { useChartColors, ChartColorSettings } from '../contexts/ChartColorContext';
import { useIndicatorPopup } from '../contexts/IndicatorPopupContext';
import MASettingsDialog from './MASettingsDialog';
import IchimokuSettingsDialog from './IchimokuSettingsDialog';

const DRAWER_WIDTH = 360;

// 패널 타입
type PanelType = 'indicator' | 'strategy';

const IndicatorConfigPanel: React.FC = () => {
  const [menuAnchor, setMenuAnchor] = useState<null | HTMLElement>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [activePanel, setActivePanel] = useState<PanelType>('indicator');
  const { openPopup } = useIndicatorPopup();
  const { settings: visibilitySettings, updateSettings: updateVisibilitySettings, updateMALines } = useIndicatorVisibility();
  
  // 이동평균선 설정 다이얼로그 상태
  const [maSettingsDialogOpen, setMaSettingsDialogOpen] = useState(false);
  
  // 일목균형표 설정 다이얼로그 상태
  const [ichimokuSettingsDialogOpen, setIchimokuSettingsDialogOpen] = useState(false);
  
  // 지표 설정 상태 (파라미터 설정)
  const [indicatorParams, setIndicatorParams] = useState<IndicatorSettings>(loadIndicatorSettings);
  const { colors, updateColors } = useChartColors();
  const [localColors, setLocalColors] = useState<Partial<ChartColorSettings>>({
    macdLine: colors.macdLine,
    signalLine: colors.signalLine,
    histogramPositive: colors.histogramPositive,
    histogramNegative: colors.histogramNegative,
    stochasticK: colors.stochasticK,
    stochasticD: colors.stochasticD,
    // 이동평균선 색상
    ma10Color: colors.ma10Color,
    ma20Color: colors.ma20Color,
    ma60Color: colors.ma60Color,
    ma120Color: colors.ma120Color,
    ma200Color: colors.ma200Color,
    ma300Color: colors.ma300Color,
    ma480Color: colors.ma480Color,
    // 이동평균선 굵기
    ma10Width: colors.ma10Width,
    ma20Width: colors.ma20Width,
    ma60Width: colors.ma60Width,
    ma120Width: colors.ma120Width,
    ma200Width: colors.ma200Width,
    ma300Width: colors.ma300Width,
    ma480Width: colors.ma480Width,
    // 일목균형표 색상
    ichimokuTenkan: colors.ichimokuTenkan,
    ichimokuKijun: colors.ichimokuKijun,
    ichimokuChikou: colors.ichimokuChikou,
    ichimokuSenkouA: colors.ichimokuSenkouA,
    ichimokuSenkouB: colors.ichimokuSenkouB,
    // 일목균형표 굵기
    ichimokuTenkanWidth: colors.ichimokuTenkanWidth,
    ichimokuKijunWidth: colors.ichimokuKijunWidth,
    ichimokuChikouWidth: colors.ichimokuChikouWidth,
    ichimokuSenkouAWidth: colors.ichimokuSenkouAWidth,
    ichimokuSenkouBWidth: colors.ichimokuSenkouBWidth,
    // 일목균형표 구름 색상
    ichimokuCloudBullish: colors.ichimokuCloudBullish,
    ichimokuCloudBearish: colors.ichimokuCloudBearish,
  });
  
  // 전략 설정 상태 (종합전략)
  const [strategySettings, setStrategySettings] = useState<IndicatorSettings>(loadIndicatorSettings);
  
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');

  // 패널 열 때마다 최신 설정 불러오기
  useEffect(() => {
    if (drawerOpen) {
      setIndicatorParams(loadIndicatorSettings());
      setStrategySettings(loadIndicatorSettings());
      setLocalColors({
        macdLine: colors.macdLine,
        signalLine: colors.signalLine,
        histogramPositive: colors.histogramPositive,
        histogramNegative: colors.histogramNegative,
        stochasticK: colors.stochasticK,
        stochasticD: colors.stochasticD,
        // 이동평균선 색상
        ma10Color: colors.ma10Color,
        ma20Color: colors.ma20Color,
        ma60Color: colors.ma60Color,
        ma120Color: colors.ma120Color,
        ma200Color: colors.ma200Color,
        ma300Color: colors.ma300Color,
        ma480Color: colors.ma480Color,
        // 이동평균선 굵기
        ma10Width: colors.ma10Width,
        ma20Width: colors.ma20Width,
        ma60Width: colors.ma60Width,
        ma120Width: colors.ma120Width,
        ma200Width: colors.ma200Width,
        ma300Width: colors.ma300Width,
        ma480Width: colors.ma480Width,
        // 일목균형표 색상
        ichimokuTenkan: colors.ichimokuTenkan,
        ichimokuKijun: colors.ichimokuKijun,
        ichimokuChikou: colors.ichimokuChikou,
        ichimokuSenkouA: colors.ichimokuSenkouA,
        ichimokuSenkouB: colors.ichimokuSenkouB,
        // 일목균형표 굵기
        ichimokuTenkanWidth: colors.ichimokuTenkanWidth,
        ichimokuKijunWidth: colors.ichimokuKijunWidth,
        ichimokuChikouWidth: colors.ichimokuChikouWidth,
        ichimokuSenkouAWidth: colors.ichimokuSenkouAWidth,
        ichimokuSenkouBWidth: colors.ichimokuSenkouBWidth,
        // 일목균형표 구름 색상
        ichimokuCloudBullish: colors.ichimokuCloudBullish,
        ichimokuCloudBearish: colors.ichimokuCloudBearish,
      });
    }
  }, [drawerOpen, colors]);

  // 메뉴 열기
  const handleMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
    setMenuAnchor(event.currentTarget);
  };

  // 메뉴 닫기
  const handleMenuClose = () => {
    setMenuAnchor(null);
  };

  // 패널 열기
  const handleOpenPanel = (panelType: PanelType) => {
    setActivePanel(panelType);
    setDrawerOpen(true);
    handleMenuClose();
  };

  // 패널 닫기
  const handleCloseDrawer = () => {
    setDrawerOpen(false);
  };

  // 지표 파라미터 설정 저장
  const handleSaveIndicatorParams = () => {
    saveIndicatorSettings(indicatorParams);
    updateColors(localColors);
    setSnackbarMessage('지표 파라미터 설정이 저장되었습니다. 차트 재로딩 시 적용됩니다.');
    setSnackbarOpen(true);
  };

  // 지표 파라미터 설정 초기화
  const handleResetIndicatorParams = () => {
    if (window.confirm('모든 지표 파라미터 설정을 기본값으로 초기화하시겠습니까?')) {
      setIndicatorParams(DEFAULT_INDICATOR_SETTINGS);
      saveIndicatorSettings(DEFAULT_INDICATOR_SETTINGS);
      setSnackbarMessage('지표 파라미터 설정이 기본값으로 초기화되었습니다.');
      setSnackbarOpen(true);
    }
  };

  // 전략 설정 저장 (종합전략)
  const handleSaveStrategy = () => {
    saveIndicatorSettings(strategySettings);
    setSnackbarMessage('전략 설정이 저장되었습니다. 차트 재로딩 시 적용됩니다.');
    setSnackbarOpen(true);
  };

  // 전략 설정 초기화 (종합전략)
  const handleResetStrategy = () => {
    if (window.confirm('모든 전략 설정을 기본값으로 초기화하시겠습니까?')) {
      setStrategySettings(DEFAULT_INDICATOR_SETTINGS);
      saveIndicatorSettings(DEFAULT_INDICATOR_SETTINGS);
      setSnackbarMessage('전략 설정이 기본값으로 초기화되었습니다.');
      setSnackbarOpen(true);
    }
  };

  // 색상 선택 컴포넌트
  const ColorPicker = ({ label, value, onChange }: { label: string; value: string; onChange: (color: string) => void }) => (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
      <Box
        sx={{
          width: 28,
          height: 28,
          borderRadius: 1,
          bgcolor: value,
          border: '2px solid',
          borderColor: 'divider',
          cursor: 'pointer',
          position: 'relative',
          overflow: 'hidden',
        }}
      >
        <input
          type="color"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            opacity: 0,
            cursor: 'pointer',
          }}
        />
      </Box>
      <Typography variant="body2" sx={{ minWidth: 80, fontSize: '12px' }}>{label}</Typography>
      <TextField
        size="small"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        sx={{ width: 80 }}
        inputProps={{ style: { fontSize: 11, padding: '4px 8px' } }}
      />
    </Box>
  );

  // 지표 설정 패널 렌더링 (파라미터 설정)
  const renderIndicatorPanel = () => (
    <>
      {/* Header */}
      <Box
        sx={{
          p: 2,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          background: 'linear-gradient(135deg, #1a237e 0%, #0d47a1 100%)',
          color: '#ffffff',
        }}
      >
        <Box>
          <Typography variant="h6" fontWeight="bold" sx={{ textShadow: '0 1px 2px rgba(0,0,0,0.3)' }}>
            지표 설정
          </Typography>
          <Typography variant="body2" sx={{ opacity: 0.9, color: 'rgba(255,255,255,0.85)' }}>
            보조지표 파라미터를 설정합니다
          </Typography>
        </Box>
        <IconButton onClick={handleCloseDrawer} sx={{ color: '#ffffff' }}>
          <CloseIcon />
        </IconButton>
      </Box>

      <Divider />

      {/* Content */}
      <Box sx={{ p: 2, overflowY: 'auto', height: 'calc(100vh - 180px)' }}>
        <Alert severity="info" sx={{ mb: 2 }}>
          <Typography variant="body2">
            보조지표의 파라미터를 설정합니다. 변경 후 저장하면 다음 차트 로딩 시 적용됩니다.
          </Typography>
        </Alert>

        {/* 이동평균선 설정 */}
        <Accordion defaultExpanded>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Typography fontWeight="bold">📈 이동평균선 설정</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Alert severity="info" sx={{ mb: 2, py: 0.5 }}>
              <Typography variant="caption">
                기간, 색상, 선굵기, SMA/EMA 유형을 설정할 수 있습니다.
              </Typography>
            </Alert>
            
            {/* MA 라인별 설정 */}
            <Box sx={{ mb: 2 }}>
              {visibilitySettings.maLines?.map((ma, index) => (
                <Box 
                  key={ma.id} 
                  sx={{ 
                    display: 'flex', 
                    alignItems: 'center', 
                    gap: 0.5, 
                    mb: 1, 
                    p: 1, 
                    borderRadius: 1,
                    bgcolor: ma.enabled ? 'action.selected' : 'action.hover',
                    opacity: ma.enabled ? 1 : 0.6,
                  }}
                >
                  {/* ON/OFF 스위치 */}
                  <Switch
                    size="small"
                    checked={ma.enabled}
                    onChange={(e) => {
                      const newLines = [...visibilitySettings.maLines];
                      newLines[index] = { ...newLines[index], enabled: e.target.checked };
                      updateMALines(newLines);
                    }}
                  />
                  
                  {/* MA ID */}
                  <Typography variant="body2" sx={{ width: 32, fontWeight: 'bold', fontSize: '11px' }}>
                    {ma.id}
                  </Typography>
                  
                  {/* 색상 미리보기 (선 모양) */}
                  <Box
                    sx={{
                      width: 20,
                      height: Math.max(ma.width * 2, 4),
                      bgcolor: ma.color,
                      borderRadius: 0.5,
                      flexShrink: 0,
                    }}
                  />
                  
                  {/* 색상 선택 */}
                  <Box sx={{ position: 'relative', width: 28, height: 28, flexShrink: 0 }}>
                    <Box
                      sx={{
                        width: 28,
                        height: 28,
                        borderRadius: 1,
                        bgcolor: ma.color,
                        border: '1px solid',
                        borderColor: 'divider',
                        cursor: 'pointer',
                        '&:hover': { boxShadow: '0 0 0 2px rgba(25, 118, 210, 0.5)' },
                      }}
                    />
                    <input
                      type="color"
                      value={ma.color}
                      onChange={(e) => {
                        const newLines = [...visibilitySettings.maLines];
                        newLines[index] = { ...newLines[index], color: e.target.value };
                        updateMALines(newLines);
                      }}
                      style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: 28,
                        height: 28,
                        opacity: 0,
                        cursor: 'pointer',
                      }}
                    />
                  </Box>
                  
                  {/* SMA/EMA 유형 */}
                  <Typography 
                    variant="caption" 
                    sx={{ 
                      width: 32, 
                      fontSize: '10px',
                      cursor: 'pointer',
                      color: 'primary.main',
                      fontWeight: 'bold',
                      textAlign: 'center',
                      '&:hover': { textDecoration: 'underline' },
                    }}
                    onClick={() => {
                      const newLines = [...visibilitySettings.maLines];
                      newLines[index] = { ...newLines[index], type: ma.type === 'SMA' ? 'EMA' : 'SMA' };
                      updateMALines(newLines);
                    }}
                  >
                    {ma.type}{ma.period}
                  </Typography>
                  
                  {/* 기간 입력 */}
                  <TextField
                    type="number"
                    size="small"
                    value={ma.period}
                    onChange={(e) => {
                      const newLines = [...visibilitySettings.maLines];
                      newLines[index] = { ...newLines[index], period: Math.max(1, Number(e.target.value)) };
                      updateMALines(newLines);
                    }}
                    inputProps={{ min: 1, max: 999, style: { padding: '4px 6px', fontSize: '11px', width: 36 } }}
                    sx={{ width: 50 }}
                  />
                  
                  {/* 굵기 선택 */}
                  <TextField
                    type="number"
                    size="small"
                    value={ma.width}
                    onChange={(e) => {
                      const newLines = [...visibilitySettings.maLines];
                      newLines[index] = { ...newLines[index], width: Math.max(0.5, Math.min(5, Number(e.target.value))) };
                      updateMALines(newLines);
                    }}
                    inputProps={{ min: 0.5, max: 5, step: 0.5, style: { padding: '4px 6px', fontSize: '11px', width: 32 } }}
                    sx={{ width: 45 }}
                  />
                </Box>
              ))}
            </Box>

            {/* 상세 설정 버튼 */}
            <Button
              variant="outlined"
              fullWidth
              onClick={() => setMaSettingsDialogOpen(true)}
              sx={{ py: 1 }}
            >
              ⚙️ 이동평균선 상세 설정
            </Button>
          </AccordionDetails>
        </Accordion>

        {/* 일목균형표 설정 */}
        <Accordion>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Typography fontWeight="bold">☁️ 일목균형표</Typography>
          </AccordionSummary>
          <AccordionDetails>
            {/* 현재 활성화된 일목균형표 요소 표시 */}
            <Box sx={{ mb: 2 }}>
              <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1 }}>
                현재 활성화된 요소:
              </Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, mb: 1.5 }}>
                {visibilitySettings.ichimokuTenkan && (
                  <Box component="span" sx={{ px: 1, py: 0.25, borderRadius: 1, bgcolor: colors.ichimokuTenkan, color: 'white', fontSize: '11px' }}>전환선</Box>
                )}
                {visibilitySettings.ichimokuKijun && (
                  <Box component="span" sx={{ px: 1, py: 0.25, borderRadius: 1, bgcolor: colors.ichimokuKijun, color: 'white', fontSize: '11px' }}>기준선</Box>
                )}
                {visibilitySettings.ichimokuChikou && (
                  <Box component="span" sx={{ px: 1, py: 0.25, borderRadius: 1, bgcolor: colors.ichimokuChikou, color: 'white', fontSize: '11px' }}>후행스팬</Box>
                )}
                {visibilitySettings.ichimokuSenkouA && (
                  <Box component="span" sx={{ px: 1, py: 0.25, borderRadius: 1, bgcolor: colors.ichimokuSenkouA, color: 'white', fontSize: '11px' }}>선행스팬1</Box>
                )}
                {visibilitySettings.ichimokuSenkouB && (
                  <Box component="span" sx={{ px: 1, py: 0.25, borderRadius: 1, bgcolor: colors.ichimokuSenkouB, color: 'white', fontSize: '11px' }}>선행스팬2</Box>
                )}
                {!visibilitySettings.ichimokuTenkan && !visibilitySettings.ichimokuKijun && !visibilitySettings.ichimokuChikou && !visibilitySettings.ichimokuSenkouA && !visibilitySettings.ichimokuSenkouB && (
                  <Typography variant="caption" color="text.secondary">없음</Typography>
                )}
              </Box>
            </Box>
            <Button
              variant="outlined"
              startIcon={<SettingsIcon />}
              onClick={() => setIchimokuSettingsDialogOpen(true)}
              sx={{ width: '100%' }}
            >
              일목균형표 상세 설정
            </Button>
          </AccordionDetails>
        </Accordion>
        

        {/* MACD 설정 */}
        <Accordion defaultExpanded>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Typography fontWeight="bold">📈 MACD</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={2}>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="단기 EMA"
                  type="number"
                  value={indicatorParams.macdFastPeriod}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, macdFastPeriod: Number(e.target.value) })}
                  inputProps={{ min: 5, max: 30 }}
                  helperText="기본: 12"
                />
              </Grid>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="장기 EMA"
                  type="number"
                  value={indicatorParams.macdSlowPeriod}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, macdSlowPeriod: Number(e.target.value) })}
                  inputProps={{ min: 10, max: 50 }}
                  helperText="기본: 26"
                />
              </Grid>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="시그널"
                  type="number"
                  value={indicatorParams.macdSignalPeriod}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, macdSignalPeriod: Number(e.target.value) })}
                  inputProps={{ min: 3, max: 20 }}
                  helperText="기본: 9"
                />
              </Grid>
            </Grid>
            <Divider sx={{ my: 2 }} />
            <Typography variant="caption" color="text.secondary" sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 1 }}>
              <Palette fontSize="small" /> 색상 설정
            </Typography>
            <Grid container spacing={1}>
              <Grid item xs={6}>
                <ColorPicker label="MACD" value={localColors.macdLine || '#f44336'} onChange={(c) => setLocalColors({ ...localColors, macdLine: c })} />
              </Grid>
              <Grid item xs={6}>
                <ColorPicker label="Signal" value={localColors.signalLine || '#ff9800'} onChange={(c) => setLocalColors({ ...localColors, signalLine: c })} />
              </Grid>
              <Grid item xs={6}>
                <ColorPicker label="Hist(+)" value={localColors.histogramPositive || '#4caf50'} onChange={(c) => setLocalColors({ ...localColors, histogramPositive: c })} />
              </Grid>
              <Grid item xs={6}>
                <ColorPicker label="Hist(-)" value={localColors.histogramNegative || '#f44336'} onChange={(c) => setLocalColors({ ...localColors, histogramNegative: c })} />
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>

        {/* Stochastic 설정 */}
        <Accordion defaultExpanded>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Typography fontWeight="bold">📊 Stochastic Slow</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Typography variant="caption" color="text.secondary" gutterBottom display="block">기간 설정</Typography>
            <Grid container spacing={2} sx={{ mb: 2 }}>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="%K"
                  type="number"
                  value={indicatorParams.stochasticKPeriod}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, stochasticKPeriod: Number(e.target.value) })}
                  inputProps={{ min: 5, max: 30 }}
                />
              </Grid>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="%D"
                  type="number"
                  value={indicatorParams.stochasticDPeriod}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, stochasticDPeriod: Number(e.target.value) })}
                  inputProps={{ min: 1, max: 10 }}
                />
              </Grid>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="Slow"
                  type="number"
                  value={indicatorParams.stochasticSlowing}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, stochasticSlowing: Number(e.target.value) })}
                  inputProps={{ min: 1, max: 10 }}
                />
              </Grid>
            </Grid>
            <Typography variant="caption" color="text.secondary" gutterBottom display="block">매매 기준값</Typography>
            <Box sx={{ px: 1 }}>
              <Typography variant="body2" sx={{ fontSize: '12px' }}>과매도: {indicatorParams.stochasticOversold}</Typography>
              <Slider
                size="small"
                value={indicatorParams.stochasticOversold}
                onChange={(_, value) => setIndicatorParams({ ...indicatorParams, stochasticOversold: value as number })}
                min={10}
                max={40}
                marks={[{ value: 20, label: '20' }]}
              />
              <Typography variant="body2" sx={{ fontSize: '12px' }}>과매수: {indicatorParams.stochasticOverbought}</Typography>
              <Slider
                size="small"
                value={indicatorParams.stochasticOverbought}
                onChange={(_, value) => setIndicatorParams({ ...indicatorParams, stochasticOverbought: value as number })}
                min={60}
                max={95}
                marks={[{ value: 80, label: '80' }]}
              />
            </Box>
            <Divider sx={{ my: 2 }} />
            <Typography variant="caption" color="text.secondary" sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 1 }}>
              <Palette fontSize="small" /> 색상 설정
            </Typography>
            <Grid container spacing={1}>
              <Grid item xs={6}>
                <ColorPicker label="%K" value={localColors.stochasticK || '#2196f3'} onChange={(c) => setLocalColors({ ...localColors, stochasticK: c })} />
              </Grid>
              <Grid item xs={6}>
                <ColorPicker label="%D" value={localColors.stochasticD || '#ff5722'} onChange={(c) => setLocalColors({ ...localColors, stochasticD: c })} />
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>

        {/* RSI 설정 */}
        <Accordion>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Typography fontWeight="bold">📉 RSI</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={2} sx={{ mb: 2 }}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  size="small"
                  label="기간"
                  type="number"
                  value={indicatorParams.rsiPeriod}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, rsiPeriod: Number(e.target.value) })}
                  inputProps={{ min: 5, max: 30 }}
                  helperText="기본: 14"
                />
              </Grid>
            </Grid>
            <Box sx={{ px: 1 }}>
              <Typography variant="body2" sx={{ fontSize: '12px' }}>과매도: {indicatorParams.rsiOversold}</Typography>
              <Slider
                size="small"
                value={indicatorParams.rsiOversold}
                onChange={(_, value) => setIndicatorParams({ ...indicatorParams, rsiOversold: value as number })}
                min={10}
                max={40}
                marks={[{ value: 30, label: '30' }]}
              />
              <Typography variant="body2" sx={{ fontSize: '12px' }}>과매수: {indicatorParams.rsiOverbought}</Typography>
              <Slider
                size="small"
                value={indicatorParams.rsiOverbought}
                onChange={(_, value) => setIndicatorParams({ ...indicatorParams, rsiOverbought: value as number })}
                min={60}
                max={90}
                marks={[{ value: 70, label: '70' }]}
              />
            </Box>
          </AccordionDetails>
        </Accordion>

        {/* CCI 설정 */}
        <Accordion>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Typography fontWeight="bold">📐 CCI</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={2}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  size="small"
                  label="기간"
                  type="number"
                  value={indicatorParams.cciPeriod}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, cciPeriod: Number(e.target.value) })}
                  inputProps={{ min: 10, max: 50 }}
                  helperText="기본: 20"
                />
              </Grid>
              <Grid item xs={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="과매도"
                  type="number"
                  value={indicatorParams.cciOversold}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, cciOversold: Number(e.target.value) })}
                  inputProps={{ min: -300, max: -50 }}
                />
              </Grid>
              <Grid item xs={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="과매수"
                  type="number"
                  value={indicatorParams.cciOverbought}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, cciOverbought: Number(e.target.value) })}
                  inputProps={{ min: 50, max: 300 }}
                />
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>

        {/* ADX 설정 */}
        <Accordion>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Typography fontWeight="bold">🔺 ADX</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={2}>
              <Grid item xs={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="기간"
                  type="number"
                  value={indicatorParams.adxPeriod}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, adxPeriod: Number(e.target.value) })}
                  inputProps={{ min: 5, max: 30 }}
                  helperText="기본: 14"
                />
              </Grid>
              <Grid item xs={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="강한추세"
                  type="number"
                  value={indicatorParams.adxStrongThreshold}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, adxStrongThreshold: Number(e.target.value) })}
                  inputProps={{ min: 15, max: 50 }}
                  helperText="기본: 25"
                />
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>

        {/* TRIX 설정 */}
        <Accordion>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Typography fontWeight="bold">📈 TRIX</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={2}>
              <Grid item xs={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="TRIX 기간"
                  type="number"
                  value={indicatorParams.trixPeriod}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, trixPeriod: Number(e.target.value) })}
                  inputProps={{ min: 5, max: 50 }}
                  helperText="기본: 12"
                />
              </Grid>
              <Grid item xs={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="Signal 기간"
                  type="number"
                  value={indicatorParams.trixSignalPeriod}
                  onChange={(e) => setIndicatorParams({ ...indicatorParams, trixSignalPeriod: Number(e.target.value) })}
                  inputProps={{ min: 1, max: 20 }}
                  helperText="기본: 9"
                />
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>
      </Box>

      {/* Footer Buttons */}
      <Box
        sx={{
          p: 2,
          borderTop: 1,
          borderColor: 'divider',
          display: 'flex',
          gap: 1,
          justifyContent: 'space-between',
        }}
      >
        <Button
          variant="outlined"
          startIcon={<RestartAlt />}
          onClick={handleResetIndicatorParams}
          sx={{ flex: 1, minWidth: 0 }}
          size="small"
        >
          초기화
        </Button>
        <Button
          variant="contained"
          startIcon={<SaveIcon />}
          onClick={handleSaveIndicatorParams}
          sx={{ flex: 1, minWidth: 0 }}
          size="small"
        >
          저장
        </Button>
        <Button
          variant="outlined"
          color="secondary"
          startIcon={<CloseIcon />}
          onClick={handleCloseDrawer}
          sx={{ flex: 1, minWidth: 0 }}
          size="small"
        >
          닫기
        </Button>
      </Box>
    </>
  );

  // 전략 설정 패널 렌더링 (종합전략)
  const renderStrategyPanel = () => (
    <>
      {/* Header */}
      <Box
        sx={{
          p: 2,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          bgcolor: 'primary.main',
          color: 'primary.contrastText',
        }}
      >
        <Box>
          <Typography variant="h6" fontWeight="bold">
            전략 설정
          </Typography>
          <Typography variant="body2" sx={{ opacity: 0.8 }}>
            종합 투자전략을 설정합니다
          </Typography>
        </Box>
        <IconButton onClick={handleCloseDrawer} sx={{ color: 'inherit' }}>
          <CloseIcon />
        </IconButton>
      </Box>

      <Divider />

      {/* Content */}
      <Box sx={{ p: 2, overflowY: 'auto', height: 'calc(100vh - 180px)' }}>
        {/* MACD 설정 */}
        <Accordion defaultExpanded={strategySettings.macdEnabled}>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Box sx={{ display: 'flex', alignItems: 'center', width: '100%', mr: 1 }}>
              <Switch
                size="small"
                checked={strategySettings.macdEnabled}
                onChange={(e) => {
                  e.stopPropagation();
                  setStrategySettings({ ...strategySettings, macdEnabled: e.target.checked });
                }}
                onClick={(e) => e.stopPropagation()}
                color="primary"
              />
              <Typography fontWeight="bold" sx={{ color: strategySettings.macdEnabled ? 'text.primary' : 'text.disabled' }}>
                📈 MACD
              </Typography>
            </Box>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={2}>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="단기 EMA"
                  type="number"
                  value={strategySettings.macdFastPeriod}
                  onChange={(e) => setStrategySettings({ ...strategySettings, macdFastPeriod: Number(e.target.value) })}
                  inputProps={{ min: 5, max: 30 }}
                  disabled={!strategySettings.macdEnabled}
                />
              </Grid>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="장기 EMA"
                  type="number"
                  value={strategySettings.macdSlowPeriod}
                  onChange={(e) => setStrategySettings({ ...strategySettings, macdSlowPeriod: Number(e.target.value) })}
                  inputProps={{ min: 10, max: 50 }}
                  disabled={!strategySettings.macdEnabled}
                />
              </Grid>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="시그널"
                  type="number"
                  value={strategySettings.macdSignalPeriod}
                  onChange={(e) => setStrategySettings({ ...strategySettings, macdSignalPeriod: Number(e.target.value) })}
                  inputProps={{ min: 3, max: 20 }}
                  disabled={!strategySettings.macdEnabled}
                />
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>

        {/* Stochastic 설정 */}
        <Accordion defaultExpanded={strategySettings.stochasticEnabled}>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Box sx={{ display: 'flex', alignItems: 'center', width: '100%', mr: 1 }}>
              <Switch
                size="small"
                checked={strategySettings.stochasticEnabled}
                onChange={(e) => {
                  e.stopPropagation();
                  setStrategySettings({ ...strategySettings, stochasticEnabled: e.target.checked });
                }}
                onClick={(e) => e.stopPropagation()}
                color="primary"
              />
              <Typography fontWeight="bold" sx={{ color: strategySettings.stochasticEnabled ? 'text.primary' : 'text.disabled' }}>
                📊 Stochastic Slow
              </Typography>
            </Box>
          </AccordionSummary>
          <AccordionDetails>
            <Typography variant="caption" color="text.secondary" gutterBottom display="block">기간 설정</Typography>
            <Grid container spacing={2} sx={{ mb: 2 }}>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="%K"
                  type="number"
                  value={strategySettings.stochasticKPeriod}
                  onChange={(e) => setStrategySettings({ ...strategySettings, stochasticKPeriod: Number(e.target.value) })}
                  inputProps={{ min: 5, max: 30 }}
                  disabled={!strategySettings.stochasticEnabled}
                />
              </Grid>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="%D"
                  type="number"
                  value={strategySettings.stochasticDPeriod}
                  onChange={(e) => setStrategySettings({ ...strategySettings, stochasticDPeriod: Number(e.target.value) })}
                  inputProps={{ min: 1, max: 10 }}
                  disabled={!strategySettings.stochasticEnabled}
                />
              </Grid>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  size="small"
                  label="Slow"
                  type="number"
                  value={strategySettings.stochasticSlowing}
                  onChange={(e) => setStrategySettings({ ...strategySettings, stochasticSlowing: Number(e.target.value) })}
                  inputProps={{ min: 1, max: 10 }}
                  disabled={!strategySettings.stochasticEnabled}
                />
              </Grid>
            </Grid>
            <Typography variant="caption" color="text.secondary" gutterBottom display="block">매매 기준값</Typography>
            <Box sx={{ px: 1 }}>
              <Typography variant="body2" sx={{ fontSize: '12px' }}>과매도: {strategySettings.stochasticOversold}</Typography>
              <Slider
                size="small"
                value={strategySettings.stochasticOversold}
                onChange={(_, value) => setStrategySettings({ ...strategySettings, stochasticOversold: value as number })}
                min={10}
                max={40}
                marks={[{ value: 20, label: '20' }]}
                disabled={!strategySettings.stochasticEnabled}
              />
              <Typography variant="body2" sx={{ fontSize: '12px' }}>중앙값: {strategySettings.stochasticNeutral}</Typography>
              <Slider
                size="small"
                value={strategySettings.stochasticNeutral}
                onChange={(_, value) => setStrategySettings({ ...strategySettings, stochasticNeutral: value as number })}
                min={40}
                max={60}
                marks={[{ value: 50, label: '50' }]}
                disabled={!strategySettings.stochasticEnabled}
              />
              <Typography variant="body2" sx={{ fontSize: '12px' }}>과매수: {strategySettings.stochasticOverbought}</Typography>
              <Slider
                size="small"
                value={strategySettings.stochasticOverbought}
                onChange={(_, value) => setStrategySettings({ ...strategySettings, stochasticOverbought: value as number })}
                min={60}
                max={95}
                marks={[{ value: 80, label: '80' }]}
                disabled={!strategySettings.stochasticEnabled}
              />
            </Box>
          </AccordionDetails>
        </Accordion>

        {/* RSI 설정 */}
        <Accordion defaultExpanded={strategySettings.rsiEnabled}>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Box sx={{ display: 'flex', alignItems: 'center', width: '100%', mr: 1 }}>
              <Switch
                size="small"
                checked={strategySettings.rsiEnabled}
                onChange={(e) => {
                  e.stopPropagation();
                  setStrategySettings({ ...strategySettings, rsiEnabled: e.target.checked });
                }}
                onClick={(e) => e.stopPropagation()}
                color="primary"
              />
              <Typography fontWeight="bold" sx={{ color: strategySettings.rsiEnabled ? 'text.primary' : 'text.disabled' }}>
                📉 RSI
              </Typography>
            </Box>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={2} sx={{ mb: 2 }}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  size="small"
                  label="기간"
                  type="number"
                  value={strategySettings.rsiPeriod}
                  onChange={(e) => setStrategySettings({ ...strategySettings, rsiPeriod: Number(e.target.value) })}
                  inputProps={{ min: 5, max: 30 }}
                  disabled={!strategySettings.rsiEnabled}
                />
              </Grid>
            </Grid>
            <Box sx={{ px: 1 }}>
              <Typography variant="body2" sx={{ fontSize: '12px' }}>과매도: {strategySettings.rsiOversold}</Typography>
              <Slider
                size="small"
                value={strategySettings.rsiOversold}
                onChange={(_, value) => setStrategySettings({ ...strategySettings, rsiOversold: value as number })}
                min={10}
                max={40}
                marks={[{ value: 30, label: '30' }]}
                disabled={!strategySettings.rsiEnabled}
              />
              <Typography variant="body2" sx={{ fontSize: '12px' }}>과매수: {strategySettings.rsiOverbought}</Typography>
              <Slider
                size="small"
                value={strategySettings.rsiOverbought}
                onChange={(_, value) => setStrategySettings({ ...strategySettings, rsiOverbought: value as number })}
                min={60}
                max={90}
                marks={[{ value: 70, label: '70' }]}
                disabled={!strategySettings.rsiEnabled}
              />
            </Box>
          </AccordionDetails>
        </Accordion>

        {/* CCI 설정 */}
        <Accordion defaultExpanded={strategySettings.cciEnabled}>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Box sx={{ display: 'flex', alignItems: 'center', width: '100%', mr: 1 }}>
              <Switch
                size="small"
                checked={strategySettings.cciEnabled}
                onChange={(e) => {
                  e.stopPropagation();
                  setStrategySettings({ ...strategySettings, cciEnabled: e.target.checked });
                }}
                onClick={(e) => e.stopPropagation()}
                color="primary"
              />
              <Typography fontWeight="bold" sx={{ color: strategySettings.cciEnabled ? 'text.primary' : 'text.disabled' }}>
                📐 CCI
              </Typography>
            </Box>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={2} sx={{ mb: 2 }}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  size="small"
                  label="기간"
                  type="number"
                  value={strategySettings.cciPeriod}
                  onChange={(e) => setStrategySettings({ ...strategySettings, cciPeriod: Number(e.target.value) })}
                  inputProps={{ min: 10, max: 50 }}
                  disabled={!strategySettings.cciEnabled}
                />
              </Grid>
            </Grid>
            <Grid container spacing={2}>
              <Grid item xs={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="과매도"
                  type="number"
                  value={strategySettings.cciOversold}
                  onChange={(e) => setStrategySettings({ ...strategySettings, cciOversold: Number(e.target.value) })}
                  inputProps={{ min: -300, max: -50 }}
                  disabled={!strategySettings.cciEnabled}
                />
              </Grid>
              <Grid item xs={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="과매수"
                  type="number"
                  value={strategySettings.cciOverbought}
                  onChange={(e) => setStrategySettings({ ...strategySettings, cciOverbought: Number(e.target.value) })}
                  inputProps={{ min: 50, max: 300 }}
                  disabled={!strategySettings.cciEnabled}
                />
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>

        {/* ADX 설정 */}
        <Accordion defaultExpanded={strategySettings.adxEnabled}>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Box sx={{ display: 'flex', alignItems: 'center', width: '100%', mr: 1 }}>
              <Switch
                size="small"
                checked={strategySettings.adxEnabled}
                onChange={(e) => {
                  e.stopPropagation();
                  setStrategySettings({ ...strategySettings, adxEnabled: e.target.checked });
                }}
                onClick={(e) => e.stopPropagation()}
                color="primary"
              />
              <Typography fontWeight="bold" sx={{ color: strategySettings.adxEnabled ? 'text.primary' : 'text.disabled' }}>
                🔺 ADX
              </Typography>
            </Box>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={2}>
              <Grid item xs={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="기간"
                  type="number"
                  value={strategySettings.adxPeriod}
                  onChange={(e) => setStrategySettings({ ...strategySettings, adxPeriod: Number(e.target.value) })}
                  inputProps={{ min: 5, max: 30 }}
                  disabled={!strategySettings.adxEnabled}
                />
              </Grid>
              <Grid item xs={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="강한추세"
                  type="number"
                  value={strategySettings.adxStrongThreshold}
                  onChange={(e) => setStrategySettings({ ...strategySettings, adxStrongThreshold: Number(e.target.value) })}
                  inputProps={{ min: 15, max: 50 }}
                  disabled={!strategySettings.adxEnabled}
                />
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>

        <Alert severity="info" sx={{ mt: 2 }}>
          <Typography variant="body2">
            변경 후 <strong>저장</strong> 버튼을 눌러야 적용됩니다.
            차트 다시 로딩 시 반영됩니다.
          </Typography>
        </Alert>
      </Box>

      {/* Footer Buttons */}
      <Box
        sx={{
          p: 2,
          borderTop: 1,
          borderColor: 'divider',
          display: 'flex',
          gap: 1,
          justifyContent: 'space-between',
        }}
      >
        <Button
          variant="outlined"
          startIcon={<RestartAlt />}
          onClick={handleResetStrategy}
          sx={{ flex: 1, minWidth: 0 }}
          size="small"
        >
          초기화
        </Button>
        <Button
          variant="contained"
          startIcon={<SaveIcon />}
          onClick={handleSaveStrategy}
          sx={{ flex: 1, minWidth: 0 }}
          size="small"
        >
          저장
        </Button>
        <Button
          variant="outlined"
          color="secondary"
          startIcon={<CloseIcon />}
          onClick={handleCloseDrawer}
          sx={{ flex: 1, minWidth: 0 }}
          size="small"
        >
          닫기
        </Button>
      </Box>
    </>
  );

  return (
    <>
      {/* Floating Icon Button - 우측 하단 */}
      <Tooltip title="설정" placement="left">
        <IconButton
          onClick={handleMenuOpen}
          sx={{
            position: 'fixed',
            bottom: 24,
            right: 24,
            zIndex: 1200,
            color: 'text.secondary',
            '&:hover': {
              color: 'primary.main',
              transform: 'rotate(30deg)',
              transition: 'transform 0.3s ease',
              bgcolor: 'transparent',
            },
          }}
        >
          <SettingsIcon sx={{ fontSize: 28 }} />
        </IconButton>
      </Tooltip>

      {/* Settings Menu */}
      <Menu
        anchorEl={menuAnchor}
        open={Boolean(menuAnchor)}
        onClose={handleMenuClose}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'left',
        }}
        transformOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
      >
        <MenuItem onClick={() => handleOpenPanel('indicator')}>
          <ListItemIcon>
            <TrendingUp fontSize="small" />
          </ListItemIcon>
          <ListItemText primary="지표 설정" secondary="지표 파라미터 설정" />
        </MenuItem>
        <MenuItem onClick={() => handleOpenPanel('strategy')}>
          <ListItemIcon>
            <Visibility fontSize="small" />
          </ListItemIcon>
          <ListItemText primary="전략 설정" secondary="표시할 지표 선택" />
        </MenuItem>
        <MenuItem onClick={() => { openPopup(); handleMenuClose(); }}>
          <ListItemIcon>
            <PopupIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText primary="보조지표 팝업" secondary="별도 창에서 보조지표 확인" />
        </MenuItem>
      </Menu>

      {/* Settings Drawer */}
      <Drawer
        anchor="right"
        open={drawerOpen}
        onClose={handleCloseDrawer}
        sx={{
          '& .MuiDrawer-paper': {
            width: DRAWER_WIDTH,
            boxSizing: 'border-box',
            p: 0,
          },
        }}
      >
        {activePanel === 'indicator' ? renderIndicatorPanel() : renderStrategyPanel()}
      </Drawer>

      {/* Success Snackbar */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={() => setSnackbarOpen(false)}
        message={snackbarMessage}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      />

      {/* 이동평균선 설정 다이얼로그 */}
      <MASettingsDialog
        open={maSettingsDialogOpen}
        onClose={() => setMaSettingsDialogOpen(false)}
      />
      
      {/* 일목균형표 설정 다이얼로그 */}
      <IchimokuSettingsDialog
        open={ichimokuSettingsDialogOpen}
        onClose={() => setIchimokuSettingsDialogOpen(false)}
      />
    </>
  );
};

export default IndicatorConfigPanel;
