import React, { useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Grid,
  Button,
  Tooltip,
  Slider,
  Switch,
  FormControlLabel,
  Divider,
} from '@mui/material';
import { Refresh } from '@mui/icons-material';
import { useChartColors } from '../contexts/ChartColorContext';
import { useIndicatorVisibility } from '../contexts/IndicatorVisibilityContext';

// 색상 선택 팔레트
const colorPalette = [
  '#EF5350', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5', '#2196F3', '#03A9F4', '#00BCD4',
  '#009688', '#4CAF50', '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800', '#FF5722',
  '#c62828', '#1565c0', '#2E7D32', '#F57C00', '#5D4037', '#455A64', '#000000', '#FFFFFF',
];

const CandleSettingsPanel: React.FC = () => {
  const { colors, updateColors, resetColors } = useChartColors();
  const { settings, updateSettings } = useIndicatorVisibility();
  const [colorPickerTarget, setColorPickerTarget] = useState<string | null>(null);

  // 색상 미리보기 박스
  const ColorBox: React.FC<{ colorKey: string; label: string }> = ({ colorKey, label }) => {
    const color = (colors as any)[colorKey] || '#666';
    return (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
        <Typography variant="body2" sx={{ minWidth: 80 }}>
          {label}
        </Typography>
        <Box sx={{ position: 'relative' }}>
          <Box
            onClick={() => setColorPickerTarget(colorPickerTarget === colorKey ? null : colorKey)}
            sx={{
              width: 40,
              height: 40,
              backgroundColor: color,
              borderRadius: 1,
              border: '2px solid',
              borderColor: 'divider',
              cursor: 'pointer',
              '&:hover': {
                boxShadow: '0 0 0 2px rgba(25, 118, 210, 0.5)',
              },
            }}
          />
          
          {/* 색상 팔레트 팝업 */}
          {colorPickerTarget === colorKey && (
            <Paper
              sx={{
                position: 'absolute',
                top: 44,
                left: 0,
                zIndex: 1000,
                p: 1,
                display: 'grid',
                gridTemplateColumns: 'repeat(8, 1fr)',
                gap: 0.5,
                width: 220,
                boxShadow: 3,
              }}
            >
              {colorPalette.map((c) => (
                <Box
                  key={c}
                  onClick={() => {
                    updateColors({ [colorKey]: c });
                    setColorPickerTarget(null);
                  }}
                  sx={{
                    width: 22,
                    height: 22,
                    backgroundColor: c,
                    borderRadius: 0.5,
                    border: color === c ? '2px solid #1976d2' : '1px solid #ccc',
                    cursor: 'pointer',
                    '&:hover': { transform: 'scale(1.15)' },
                  }}
                />
              ))}
              <Box sx={{ gridColumn: 'span 8', mt: 1 }}>
                <input
                  type="color"
                  value={color}
                  onChange={(e) => {
                    updateColors({ [colorKey]: e.target.value });
                    setColorPickerTarget(null);
                  }}
                  style={{ width: '100%', height: 28, cursor: 'pointer', border: 'none' }}
                />
              </Box>
            </Paper>
          )}
        </Box>
        <Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
          {color}
        </Typography>
      </Box>
    );
  };

  const handleReset = () => {
    updateColors({
      candleRising: '#c62828',
      candleFalling: '#1565c0',
    });
  };

  return (
    <Box>
      {/* 헤더 */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="subtitle1" fontWeight="bold">
          🕯️ 캔들차트 설정
        </Typography>
        <Tooltip title="초기화">
          <Button startIcon={<Refresh />} onClick={handleReset} size="small" color="inherit">
            초기화
          </Button>
        </Tooltip>
      </Box>

      {/* 캔들 색상 설정 */}
      <Paper sx={{ p: 3, mb: 3 }}>
        <Typography variant="body1" fontWeight="bold" sx={{ mb: 2 }}>
          🎨 캔들 색상
        </Typography>
        
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          <ColorBox colorKey="candleRising" label="상승 캔들" />
          <ColorBox colorKey="candleFalling" label="하락 캔들" />
        </Box>

        <Box sx={{ mt: 3, p: 2, bgcolor: 'action.hover', borderRadius: 1 }}>
          <Typography variant="caption" color="text.secondary">
            💡 미리보기
          </Typography>
          <Box sx={{ display: 'flex', gap: 3, mt: 1, alignItems: 'flex-end' }}>
            {/* 상승 캔들 미리보기 */}
            <Box sx={{ textAlign: 'center' }}>
              <Box
                sx={{
                  width: 24,
                  height: 60,
                  bgcolor: colors.candleRising,
                  borderRadius: 0.5,
                  position: 'relative',
                  mx: 'auto',
                  '&::before': {
                    content: '""',
                    position: 'absolute',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    top: -10,
                    width: 2,
                    height: 10,
                    bgcolor: colors.candleRising,
                  },
                  '&::after': {
                    content: '""',
                    position: 'absolute',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    bottom: -10,
                    width: 2,
                    height: 10,
                    bgcolor: colors.candleRising,
                  },
                }}
              />
              <Typography variant="caption" sx={{ mt: 2, display: 'block' }}>상승</Typography>
            </Box>
            
            {/* 하락 캔들 미리보기 */}
            <Box sx={{ textAlign: 'center' }}>
              <Box
                sx={{
                  width: 24,
                  height: 40,
                  bgcolor: colors.candleFalling,
                  borderRadius: 0.5,
                  position: 'relative',
                  mx: 'auto',
                  '&::before': {
                    content: '""',
                    position: 'absolute',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    top: -12,
                    width: 2,
                    height: 12,
                    bgcolor: colors.candleFalling,
                  },
                  '&::after': {
                    content: '""',
                    position: 'absolute',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    bottom: -8,
                    width: 2,
                    height: 8,
                    bgcolor: colors.candleFalling,
                  },
                }}
              />
              <Typography variant="caption" sx={{ mt: 2, display: 'block' }}>하락</Typography>
            </Box>
          </Box>
        </Box>
      </Paper>

      {/* 차트 표시 옵션 */}
      <Paper sx={{ p: 3, mb: 3 }}>
        <Typography variant="body1" fontWeight="bold" sx={{ mb: 2 }}>
          📊 차트 표시 옵션
        </Typography>
        
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <FormControlLabel
            control={
              <Switch
                checked={settings.showGrid !== false}
                onChange={(e) => updateSettings({ showGrid: e.target.checked })}
              />
            }
            label="그리드 표시"
          />
          <FormControlLabel
            control={
              <Switch
                checked={settings.tooltipEnabled !== false}
                onChange={(e) => updateSettings({ tooltipEnabled: e.target.checked })}
              />
            }
            label="툴팁 표시"
          />
        </Box>
      </Paper>

      {/* 안내 */}
      <Box sx={{ p: 2, bgcolor: 'info.light', borderRadius: 1 }}>
        <Typography variant="caption" color="info.contrastText">
          💡 <strong>캔들차트 읽기</strong><br />
          • 상승 캔들: 종가 &gt; 시가 (가격 상승)<br />
          • 하락 캔들: 종가 &lt; 시가 (가격 하락)<br />
          • 캔들 몸통: 시가~종가 범위<br />
          • 꼬리(심지): 고가~저가 범위
        </Typography>
      </Box>
    </Box>
  );
};

export default CandleSettingsPanel;

