import React, { useState } from 'react';
import {
  Box,
  Grid,
  TextField,
  Typography,
  Divider,
  Button,
  Alert,
} from '@mui/material';
import { RestartAlt } from '@mui/icons-material';
import { useChartColors, ChartColorSettings } from '../../contexts/ChartColorContext';

const ChartColorSettingsTab: React.FC = () => {
  const { colors, updateColors, resetColors } = useChartColors();
  const [tempColors, setTempColors] = useState<ChartColorSettings>(colors);
  const [success, setSuccess] = useState(false);

  React.useEffect(() => {
    setTempColors(colors);
  }, [colors]);

  const handleColorChange = (key: keyof ChartColorSettings, value: string | number) => {
    setTempColors(prev => ({ ...prev, [key]: value }));
  };

  const handleSave = () => {
    updateColors(tempColors);
    setSuccess(true);
    setTimeout(() => setSuccess(false), 3000);
  };

  const handleReset = () => {
    if (window.confirm('모든 색상 설정을 기본값으로 초기화하시겠습니까?')) {
      resetColors();
      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    }
  };

  const ColorInput = ({ label, colorKey }: { label: string; colorKey: keyof ChartColorSettings }) => {
    const colorValue = String(tempColors[colorKey]);
    return (
      <Grid container spacing={1} alignItems="center" sx={{ mb: 2 }}>
        <Grid item xs={6}>
          <Typography variant="body2">{label}</Typography>
        </Grid>
        <Grid item xs={4}>
          <TextField
            fullWidth
            size="small"
            type="text"
            value={colorValue}
            onChange={(e) => handleColorChange(colorKey, e.target.value)}
          />
        </Grid>
        <Grid item xs={2}>
          <Box
            sx={{
              width: '100%',
              height: 36,
              backgroundColor: colorValue,
              border: '1px solid #ccc',
              borderRadius: 1,
              cursor: 'pointer',
            }}
            onClick={() => {
              const input = document.createElement('input');
              input.type = 'color';
              input.value = colorValue;
              input.onchange = (e) => {
                handleColorChange(colorKey, (e.target as HTMLInputElement).value);
              };
              input.click();
            }}
          />
        </Grid>
      </Grid>
    );
  };

  const MASettingInput = ({ 
    label, 
    colorKey, 
    widthKey 
  }: { 
    label: string; 
    colorKey: keyof ChartColorSettings; 
    widthKey: keyof ChartColorSettings;
  }) => {
    const colorValue = String(tempColors[colorKey]);
    const widthValue = Number(tempColors[widthKey]);
    return (
      <Grid container spacing={1} alignItems="center" sx={{ mb: 2 }}>
        <Grid item xs={3}>
          <Typography variant="body2">{label}</Typography>
        </Grid>
        <Grid item xs={3}>
          <TextField
            fullWidth
            size="small"
            type="text"
            value={colorValue}
            onChange={(e) => handleColorChange(colorKey, e.target.value)}
            placeholder="색상"
          />
        </Grid>
        <Grid item xs={2}>
          <Box
            sx={{
              width: '100%',
              height: 36,
              backgroundColor: colorValue,
              border: '1px solid #ccc',
              borderRadius: 1,
              cursor: 'pointer',
            }}
            onClick={() => {
              const input = document.createElement('input');
              input.type = 'color';
              input.value = colorValue;
              input.onchange = (e) => {
                handleColorChange(colorKey, (e.target as HTMLInputElement).value);
              };
              input.click();
            }}
          />
        </Grid>
        <Grid item xs={2}>
          <TextField
            fullWidth
            size="small"
            type="number"
            value={widthValue}
            onChange={(e) => handleColorChange(widthKey, Number(e.target.value))}
            inputProps={{ min: 0.5, max: 5, step: 0.5 }}
            placeholder="굵기"
          />
        </Grid>
        <Grid item xs={2}>
          <Box
            sx={{
              width: '100%',
              height: 36,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Box
              sx={{
                width: '100%',
                height: `${widthValue * 2}px`,
                backgroundColor: colorValue,
                borderRadius: 1,
              }}
            />
          </Box>
        </Grid>
      </Grid>
    );
  };

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6">
          차트 색상 설정
        </Typography>
        <Button
          variant="outlined"
          size="small"
          startIcon={<RestartAlt />}
          onClick={handleReset}
          color="secondary"
        >
          초기화
        </Button>
      </Box>

      {success && (
        <Alert severity="success" sx={{ mb: 2 }}>
          설정이 저장되었습니다.
        </Alert>
      )}

      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 'bold', mb: 2 }}>
          🕯️ 캔들 색상
        </Typography>
        <ColorInput label="상승 캔들" colorKey="candleRising" />
        <ColorInput label="하락 캔들" colorKey="candleFalling" />
      </Box>

      <Divider sx={{ my: 2 }} />

      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 'bold', mb: 2 }}>
          📈 이동평균선 설정 (색상 및 굵기)
        </Typography>
        <Grid container spacing={1} sx={{ mb: 1 }}>
          <Grid item xs={3}><Typography variant="caption" color="text.secondary">이름</Typography></Grid>
          <Grid item xs={3}><Typography variant="caption" color="text.secondary">색상 코드</Typography></Grid>
          <Grid item xs={2}><Typography variant="caption" color="text.secondary">색상</Typography></Grid>
          <Grid item xs={2}><Typography variant="caption" color="text.secondary">굵기</Typography></Grid>
          <Grid item xs={2}><Typography variant="caption" color="text.secondary">미리보기</Typography></Grid>
        </Grid>
        <MASettingInput label="MA10 (10일)" colorKey="ma10Color" widthKey="ma10Width" />
        <MASettingInput label="MA20 (20일)" colorKey="ma20Color" widthKey="ma20Width" />
        <MASettingInput label="MA60 (60일)" colorKey="ma60Color" widthKey="ma60Width" />
        <MASettingInput label="MA120 (120일)" colorKey="ma120Color" widthKey="ma120Width" />
        <MASettingInput label="MA200 (200일)" colorKey="ma200Color" widthKey="ma200Width" />
        <MASettingInput label="MA300 (300일)" colorKey="ma300Color" widthKey="ma300Width" />
        <MASettingInput label="MA480 (480일)" colorKey="ma480Color" widthKey="ma480Width" />
      </Box>
      
      <Divider sx={{ my: 2 }} />
      
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 'bold', mb: 2 }}>
          📊 MACD 이동평균선 색상 (12/26/60일)
        </Typography>
        <ColorInput label="12일 이동평균선" colorKey="ma12" />
        <ColorInput label="26일 이동평균선" colorKey="ma26" />
        <ColorInput label="60일 이동평균선" colorKey="ma60" />
      </Box>

      <Divider sx={{ my: 2 }} />

      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 'bold', mb: 2 }}>
          📊 거래량 색상
        </Typography>
        <ColorInput label="상승 거래량" colorKey="volumeRising" />
        <ColorInput label="하락 거래량" colorKey="volumeFalling" />
      </Box>

      <Divider sx={{ my: 2 }} />

      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 'bold', mb: 2 }}>
          📉 MACD 색상
        </Typography>
        <ColorInput label="MACD 라인" colorKey="macdLine" />
        <ColorInput label="Signal 라인" colorKey="signalLine" />
        <ColorInput label="히스토그램 (양수)" colorKey="histogramPositive" />
        <ColorInput label="히스토그램 (음수)" colorKey="histogramNegative" />
      </Box>

      <Divider sx={{ my: 2 }} />

      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 'bold', mb: 2 }}>
          📊 Stochastic Slow 색상
        </Typography>
        <ColorInput label="%K 라인" colorKey="stochasticK" />
        <ColorInput label="%D 라인" colorKey="stochasticD" />
      </Box>

      <Divider sx={{ my: 2 }} />

      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 'bold', mb: 2 }}>
          ☁️ 일목균형표 설정 (색상 및 굵기)
        </Typography>
        <Grid container spacing={1} sx={{ mb: 1 }}>
          <Grid item xs={3}><Typography variant="caption" color="text.secondary">이름</Typography></Grid>
          <Grid item xs={3}><Typography variant="caption" color="text.secondary">색상 코드</Typography></Grid>
          <Grid item xs={2}><Typography variant="caption" color="text.secondary">색상</Typography></Grid>
          <Grid item xs={2}><Typography variant="caption" color="text.secondary">굵기</Typography></Grid>
          <Grid item xs={2}><Typography variant="caption" color="text.secondary">미리보기</Typography></Grid>
        </Grid>
        <MASettingInput label="전환선 (9일)" colorKey="ichimokuTenkan" widthKey="ichimokuTenkanWidth" />
        <MASettingInput label="기준선 (26일)" colorKey="ichimokuKijun" widthKey="ichimokuKijunWidth" />
        <MASettingInput label="후행스팬" colorKey="ichimokuChikou" widthKey="ichimokuChikouWidth" />
        <MASettingInput label="선행스팬1" colorKey="ichimokuSenkouA" widthKey="ichimokuSenkouAWidth" />
        <MASettingInput label="선행스팬2" colorKey="ichimokuSenkouB" widthKey="ichimokuSenkouBWidth" />
        
        <Divider sx={{ my: 2 }} />
        <Typography variant="body2" sx={{ mb: 1, fontWeight: 'bold' }}>구름 영역 색상</Typography>
        <ColorInput label="상승 구름 (녹색)" colorKey="ichimokuCloudBullish" />
        <ColorInput label="하락 구름 (빨간색)" colorKey="ichimokuCloudBearish" />
      </Box>

      <Divider sx={{ my: 3 }} />

      <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
        <Button variant="contained" onClick={handleSave}>
          저장
        </Button>
      </Box>
    </Box>
  );
};

export default ChartColorSettingsTab;
