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

// 색상 선택 팔레트
const colorPalette = [
  '#EF5350', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5', '#2196F3', '#03A9F4', '#00BCD4',
  '#009688', '#4CAF50', '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800', '#FF5722',
  '#795548', '#9E9E9E', '#607D8B', '#000000', '#26A69A', '#42A5F5', '#66BB6A', '#FFCA28',
];

const IchimokuSettingsPanel: React.FC = () => {
  const { settings, updateSettings } = useIndicatorVisibility();
  const { colors, updateColors } = useChartColors();

  const [colorPickerTarget, setColorPickerTarget] = useState<string | null>(null);

  // 색상 미리보기 박스
  const ColorBox: React.FC<{ colorKey: string }> = ({ colorKey }) => {
    const color = (colors as any)[colorKey] || '#666';
    return (
      <Box sx={{ position: 'relative' }}>
        <Box
          onClick={() => setColorPickerTarget(colorPickerTarget === colorKey ? null : colorKey)}
          sx={{
            width: 28,
            height: 28,
            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: 32,
              left: 0,
              zIndex: 1000,
              p: 1,
              display: 'grid',
              gridTemplateColumns: 'repeat(8, 1fr)',
              gap: 0.5,
              width: 200,
              boxShadow: 3,
            }}
          >
            {colorPalette.map((c) => (
              <Box
                key={c}
                onClick={() => {
                  updateColors({ [colorKey]: c });
                  setColorPickerTarget(null);
                }}
                sx={{
                  width: 20,
                  height: 20,
                  backgroundColor: c,
                  borderRadius: 0.5,
                  border: color === c ? '2px solid #1976d2' : '1px solid #ccc',
                  cursor: 'pointer',
                  '&:hover': { transform: 'scale(1.2)' },
                }}
              />
            ))}
            <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: 24, cursor: 'pointer', border: 'none' }}
              />
            </Box>
          </Paper>
        )}
      </Box>
    );
  };

  const handleReset = () => {
    updateSettings({
      ichimokuTenkan: false,
      ichimokuKijun: false,
      ichimokuChikou: false,
      ichimokuSenkouA: false,
      ichimokuSenkouB: false,
      ichimokuTenkanPeriod: 9,
      ichimokuKijunPeriod: 26,
      ichimokuSenkouBPeriod: 52,
    });
    updateColors({
      ichimokuTenkan: '#EF5350',
      ichimokuKijun: '#42A5F5',
      ichimokuChikou: '#66BB6A',
      ichimokuSenkouA: '#26A69A',
      ichimokuSenkouB: '#EF5350',
      ichimokuTenkanWidth: 1,
      ichimokuKijunWidth: 1.5,
      ichimokuChikouWidth: 1,
      ichimokuSenkouAWidth: 1,
      ichimokuSenkouBWidth: 1,
      ichimokuCloudBullish: 'rgba(239, 83, 80, 0.2)',
      ichimokuCloudBearish: 'rgba(38, 166, 154, 0.2)',
    });
  };

  // 일목균형표 항목 렌더링
  const renderIchimokuItem = (
    label: string,
    description: string,
    enabledKey: string,
    colorKey: string,
    widthKey: string,
    periodKey?: string
  ) => {
    const isEnabled = (settings as any)[enabledKey];
    const width = (colors as any)[widthKey] || 1;

    return (
      <Paper
        sx={{
          p: 1.5,
          mb: 1.5,
          border: '1px solid',
          borderColor: isEnabled ? 'primary.main' : 'divider',
          bgcolor: isEnabled ? 'action.selected' : 'background.paper',
        }}
      >
        <Grid container spacing={1} alignItems="center">
          {/* 활성화 스위치 */}
          <Grid item xs={1}>
            <Switch
              checked={isEnabled}
              onChange={(e) => updateSettings({ [enabledKey]: e.target.checked })}
              size="small"
            />
          </Grid>

          {/* 라벨 */}
          <Grid item xs={2}>
            <Typography
              variant="body2"
              fontWeight={isEnabled ? 'bold' : 'normal'}
              color={isEnabled ? 'text.primary' : 'text.secondary'}
              sx={{ fontSize: '12px' }}
            >
              {label}
            </Typography>
            <Typography variant="caption" color="text.secondary" sx={{ fontSize: '10px' }}>
              {description}
            </Typography>
          </Grid>

          {/* 기간 (해당되는 경우) */}
          <Grid item xs={2}>
            {periodKey ? (
              <TextField
                type="number"
                value={(settings as any)[periodKey] || 9}
                onChange={(e) => updateSettings({ [periodKey]: parseInt(e.target.value) || 1 })}
                size="small"
                inputProps={{ min: 1, max: 100, style: { fontSize: 12, padding: '6px 8px' } }}
                label="기간"
                sx={{ width: 80 }}
              />
            ) : (
              <Typography variant="caption" color="text.secondary">-</Typography>
            )}
          </Grid>

          {/* 색상 */}
          <Grid item xs={1.5}>
            <ColorBox colorKey={colorKey} />
          </Grid>

          {/* 선 굵기 */}
          <Grid item xs={5.5}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Slider
                value={width}
                onChange={(_, value) => updateColors({ [widthKey]: value as number })}
                min={0.5}
                max={4}
                step={0.5}
                size="small"
                sx={{ flex: 1 }}
              />
              <Typography variant="caption" sx={{ minWidth: 30 }}>
                {width}px
              </Typography>
              <Box
                sx={{
                  width: 30,
                  height: Math.max(width * 2, 2),
                  bgcolor: (colors as any)[colorKey],
                  borderRadius: 0.5,
                }}
              />
            </Box>
          </Grid>
        </Grid>
      </Paper>
    );
  };

  return (
    <Box>
      {/* 헤더 */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="subtitle1" fontWeight="bold">
          🗻 일목균형표 설정
        </Typography>
        <Tooltip title="초기화">
          <Button startIcon={<Refresh />} onClick={handleReset} size="small" color="inherit">
            초기화
          </Button>
        </Tooltip>
      </Box>

      {/* 헤더 행 */}
      <Paper sx={{ p: 1, mb: 2, bgcolor: 'primary.main', opacity: 0.9 }}>
        <Grid container spacing={1} alignItems="center">
          <Grid item xs={1}>
            <Typography variant="caption" fontWeight="bold" color="white">사용</Typography>
          </Grid>
          <Grid item xs={2}>
            <Typography variant="caption" fontWeight="bold" color="white">이름</Typography>
          </Grid>
          <Grid item xs={2}>
            <Typography variant="caption" fontWeight="bold" color="white">기간</Typography>
          </Grid>
          <Grid item xs={1.5}>
            <Typography variant="caption" fontWeight="bold" color="white">색상</Typography>
          </Grid>
          <Grid item xs={5.5}>
            <Typography variant="caption" fontWeight="bold" color="white">선 굵기</Typography>
          </Grid>
        </Grid>
      </Paper>

      {/* 각 일목균형표 항목 */}
      {renderIchimokuItem('전환선', '단기 추세', 'ichimokuTenkan', 'ichimokuTenkan', 'ichimokuTenkanWidth', 'ichimokuTenkanPeriod')}
      {renderIchimokuItem('기준선', '중기 추세', 'ichimokuKijun', 'ichimokuKijun', 'ichimokuKijunWidth', 'ichimokuKijunPeriod')}
      {renderIchimokuItem('후행스팬', '현재가격 26일 후행', 'ichimokuChikou', 'ichimokuChikou', 'ichimokuChikouWidth')}
      {renderIchimokuItem('선행스팬1', '구름대 상단', 'ichimokuSenkouA', 'ichimokuSenkouA', 'ichimokuSenkouAWidth')}
      {renderIchimokuItem('선행스팬2', '구름대 하단', 'ichimokuSenkouB', 'ichimokuSenkouB', 'ichimokuSenkouBWidth', 'ichimokuSenkouBPeriod')}

      {/* 구름대 색상 설정 */}
      <Paper sx={{ p: 2, mt: 2, border: '1px solid', borderColor: 'divider' }}>
        <Typography variant="body2" fontWeight="bold" sx={{ mb: 1.5 }}>
          ☁️ 구름대 색상
        </Typography>
        <Grid container spacing={2}>
          <Grid item xs={6}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography variant="caption" sx={{ minWidth: 60 }}>상승 구름</Typography>
              <ColorBox colorKey="ichimokuCloudBullish" />
            </Box>
          </Grid>
          <Grid item xs={6}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography variant="caption" sx={{ minWidth: 60 }}>하락 구름</Typography>
              <ColorBox colorKey="ichimokuCloudBearish" />
            </Box>
          </Grid>
        </Grid>
      </Paper>

      {/* 안내 */}
      <Alert severity="info" sx={{ mt: 2 }}>
        <Typography variant="caption">
          💡 일목균형표는 추세 분석에 사용되는 기술적 지표입니다.<br />
          • 전환선이 기준선 위 = 상승 추세, 아래 = 하락 추세<br />
          • 가격이 구름대 위 = 강세, 아래 = 약세
        </Typography>
      </Alert>
    </Box>
  );
};

export default IchimokuSettingsPanel;

