import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Typography,
  TextField,
  Select,
  MenuItem,
  FormControl,
  Checkbox,
  IconButton,
  Slider,
  Paper,
  Grid,
  Tooltip,
  Button,
} from '@mui/material';
import { Refresh } from '@mui/icons-material';
import { MALineConfig, defaultMALines, useIndicatorVisibility } from '../contexts/IndicatorVisibilityContext';

const MASettingsPanel: React.FC = () => {
  const { settings, updateMALines } = useIndicatorVisibility();
  const [maLines, setMALines] = useState<MALineConfig[]>([]);

  // 초기화
  useEffect(() => {
    setMALines(settings.maLines ? [...settings.maLines] : [...defaultMALines]);
  }, [settings.maLines]);

  // 변경사항 자동 저장 (debounce)
  const saveChanges = useCallback((lines: MALineConfig[]) => {
    updateMALines(lines);
  }, [updateMALines]);

  const handleToggle = (index: number) => {
    const newLines = [...maLines];
    newLines[index] = { ...newLines[index], enabled: !newLines[index].enabled };
    setMALines(newLines);
    saveChanges(newLines);
  };

  const handlePeriodChange = (index: number, value: number) => {
    const newLines = [...maLines];
    newLines[index] = { ...newLines[index], period: value };
    setMALines(newLines);
    saveChanges(newLines);
  };

  const handleColorChange = (index: number, color: string) => {
    const newLines = [...maLines];
    newLines[index] = { ...newLines[index], color };
    setMALines(newLines);
    saveChanges(newLines);
  };

  const handleWidthChange = (index: number, width: number) => {
    const newLines = [...maLines];
    newLines[index] = { ...newLines[index], width };
    setMALines(newLines);
    saveChanges(newLines);
  };

  const handleTypeChange = (index: number, type: 'SMA' | 'EMA') => {
    const newLines = [...maLines];
    newLines[index] = { ...newLines[index], type };
    setMALines(newLines);
    saveChanges(newLines);
  };

  const handleReset = () => {
    const newLines = [...defaultMALines];
    setMALines(newLines);
    saveChanges(newLines);
  };

  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.5, 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={1.5}>
            <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={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={4.5}>
            <Typography variant="caption" fontWeight="bold" color="white">
              선 굵기
            </Typography>
          </Grid>
        </Grid>
      </Paper>

      {/* 각 MA 설정 행 */}
      {maLines.map((ma, index) => (
        <Paper 
          key={ma.id} 
          sx={{ 
            p: 1.5, 
            mb: 1.5, 
            border: '1px solid',
            borderColor: ma.enabled ? 'primary.main' : 'divider',
            bgcolor: ma.enabled ? 'action.selected' : 'background.paper',
            transition: 'all 0.2s',
          }}
        >
          <Grid container spacing={1} alignItems="center">
            {/* 활성화 체크박스 */}
            <Grid item xs={1}>
              <Checkbox
                checked={ma.enabled}
                onChange={() => handleToggle(index)}
                sx={{ p: 0.5 }}
              />
            </Grid>

            {/* 이름 */}
            <Grid item xs={1.5}>
              <Typography 
                variant="body2" 
                fontWeight={ma.enabled ? 'bold' : 'normal'}
                color={ma.enabled ? 'text.primary' : 'text.secondary'}
              >
                {ma.id}
              </Typography>
            </Grid>

            {/* 종류 (SMA/EMA) */}
            <Grid item xs={1.5}>
              <FormControl size="small" fullWidth>
                <Select
                  value={ma.type}
                  onChange={(e) => handleTypeChange(index, e.target.value as 'SMA' | 'EMA')}
                  sx={{ fontSize: '0.875rem' }}
                >
                  <MenuItem value="SMA">단순</MenuItem>
                  <MenuItem value="EMA">지수</MenuItem>
                </Select>
              </FormControl>
            </Grid>

            {/* 기간 */}
            <Grid item xs={2}>
              <TextField
                type="number"
                value={ma.period}
                onChange={(e) => handlePeriodChange(index, parseInt(e.target.value) || 1)}
                size="small"
                inputProps={{ min: 1, max: 1000 }}
                sx={{ 
                  '& .MuiInputBase-input': { 
                    textAlign: 'center',
                    fontSize: '0.875rem',
                  }
                }}
                fullWidth
              />
            </Grid>

            {/* 색상 */}
            <Grid item xs={1.5}>
              <Box sx={{ position: 'relative', display: 'inline-block' }}>
                <Box
                  sx={{
                    width: 32,
                    height: 32,
                    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) => handleColorChange(index, e.target.value)}
                  style={{ 
                    position: 'absolute', 
                    top: 0, 
                    left: 0, 
                    width: 32, 
                    height: 32, 
                    opacity: 0, 
                    cursor: 'pointer' 
                  }}
                />
              </Box>
            </Grid>

            {/* 선 굵기 */}
            <Grid item xs={4.5}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Slider
                  value={ma.width}
                  onChange={(_, value) => handleWidthChange(index, value as number)}
                  min={0.5}
                  max={5}
                  step={0.5}
                  sx={{ flex: 1 }}
                />
                <Typography variant="caption" sx={{ minWidth: 30, textAlign: 'right' }}>
                  {ma.width}px
                </Typography>
                {/* 선 미리보기 */}
                <Box
                  sx={{
                    width: 40,
                    height: Math.max(ma.width * 2, 2),
                    backgroundColor: ma.enabled ? ma.color : '#ccc',
                    borderRadius: 0.5,
                  }}
                />
              </Box>
            </Grid>
          </Grid>
        </Paper>
      ))}

      {/* 범례/안내 */}
      <Box sx={{ mt: 2, p: 1.5, bgcolor: 'info.light', borderRadius: 1, opacity: 0.8 }}>
        <Typography variant="caption" color="info.contrastText">
          💡 <strong>단순(SMA)</strong>: 단순이동평균 - 일정 기간의 종가 평균<br />
          💡 <strong>지수(EMA)</strong>: 지수이동평균 - 최근 가격에 더 높은 가중치 적용
        </Typography>
      </Box>
    </Box>
  );
};

export default MASettingsPanel;

