import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  Button,
  Box,
  Typography,
  TextField,
  Select,
  MenuItem,
  Switch,
  IconButton,
  Slider,
  Divider,
  Tooltip,
} from '@mui/material';
import { Close, Refresh } from '@mui/icons-material';
import { MALineConfig, defaultMALines, useIndicatorVisibility } from '../contexts/IndicatorVisibilityContext';
import DraggablePaper from './DraggablePaper';

interface MASettingsDialogProps {
  open: boolean;
  onClose: () => void;
  /** 멀티차트: 스토어 MA만 편집(적용 시까지 투자분석 컨텍스트 미반영) */
  multiChartToolbar?: {
    maLines: MALineConfig[];
    setMaLines: (value: MALineConfig[] | ((prev: MALineConfig[]) => MALineConfig[])) => void;
  };
}

const MASettingsDialog: React.FC<MASettingsDialogProps> = ({ open, onClose, multiChartToolbar }) => {
  const { settings, updateMALines } = useIndicatorVisibility();
  const [tempMALines, setTempMALines] = useState<MALineConfig[]>([]);

  useEffect(() => {
    if (!open || !multiChartToolbar) return;
    setTempMALines(multiChartToolbar.maLines.map((l) => ({ ...l })));
  }, [open, multiChartToolbar]);

  useEffect(() => {
    if (!open || multiChartToolbar) return;
    setTempMALines(settings.maLines ? [...settings.maLines] : [...defaultMALines]);
  }, [open, multiChartToolbar, settings.maLines]);

  const handleToggle = (index: number) => {
    const newLines = [...tempMALines];
    newLines[index] = { ...newLines[index], enabled: !newLines[index].enabled };
    setTempMALines(newLines);
    if (!multiChartToolbar) {
      updateMALines(newLines);
    }
  };

  const handlePeriodChange = (index: number, value: number) => {
    const newLines = [...tempMALines];
    newLines[index] = { ...newLines[index], period: value };
    setTempMALines(newLines);
  };

  const handleColorChange = (index: number, color: string) => {
    const newLines = [...tempMALines];
    newLines[index] = { ...newLines[index], color };
    setTempMALines(newLines);
  };

  const handleWidthChange = (index: number, width: number) => {
    const newLines = [...tempMALines];
    newLines[index] = { ...newLines[index], width };
    setTempMALines(newLines);
  };

  // ❌ EMA 사용하지 않음 - SMA만 사용
  // const handleTypeChange = (index: number, type: 'SMA' | 'EMA') => {
  //   const newLines = [...tempMALines];
  //   newLines[index] = { ...newLines[index], type };
  //   setTempMALines(newLines);
  // };

  const handleSave = () => {
    if (multiChartToolbar) {
      multiChartToolbar.setMaLines(tempMALines.map((l) => ({ ...l })));
    } else {
      console.log('💾 [MASettingsDialog] 저장 버튼 클릭 - Context 업데이트 중...');
      updateMALines(tempMALines);
      console.log('✅ [MASettingsDialog] Context 업데이트 완료');
    }
    onClose();
  };

  const handleReset = () => {
    setTempMALines([...defaultMALines]);
  };

  return (
    <Dialog 
      open={open} 
      onClose={onClose} 
      maxWidth="md" 
      fullWidth
      hideBackdrop={true}
      disableScrollLock={true}
      PaperComponent={DraggablePaper}
      sx={{
        pointerEvents: 'none',
        '& .MuiDialog-container': {
          pointerEvents: 'none',
          alignItems: 'flex-start',
        },
      }}
      PaperProps={{
        sx: { 
          borderRadius: 2,
          pointerEvents: 'auto',
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
          border: '2px solid rgba(80, 100, 160, 0.5)',
        }
      }}
    >
      <DialogTitle sx={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        bgcolor: '#1976d2',
        color: '#fff',
        py: 1.2,
      }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '16px', color: '#fff' }}>
            📊 이동평균선 설정
          </Typography>
          <Tooltip title="초기화">
            <IconButton onClick={handleReset} size="small" sx={{ color: '#fff', '&:hover': { bgcolor: 'rgba(255,255,255,0.1)' } }}>
              <Refresh />
            </IconButton>
          </Tooltip>
        </Box>
        <Box 
          sx={{ display: 'flex', alignItems: 'center', gap: 1 }}
          onMouseDown={(e) => e.stopPropagation()}
        >
          <Button 
            onClick={(e) => {
              e.stopPropagation();
              onClose();
            }}
            sx={{ 
              color: '#fff',
              borderColor: '#fff',
              '&:hover': { 
                bgcolor: 'rgba(255,255,255,0.1)',
                borderColor: '#fff'
              },
              minWidth: '70px',
              fontSize: '13px',
              fontWeight: 600,
            }}
            variant="outlined"
            size="small"
          >
            취소
          </Button>
          <Button 
            onClick={(e) => {
              e.stopPropagation();
              handleSave();
            }}
            sx={{ 
              bgcolor: '#fff',
              color: '#1976d2',
              '&:hover': { 
                bgcolor: 'rgba(255,255,255,0.9)'
              },
              minWidth: '70px',
              fontSize: '13px',
              fontWeight: 600,
            }}
            variant="contained"
            size="small"
          >
            적용
          </Button>
        </Box>
      </DialogTitle>

      <Divider />

      <DialogContent sx={{ pt: 2 }}>
        <Box sx={{ 
          display: 'flex', 
          alignItems: 'center', 
          gap: 1, 
          mb: 2, 
          p: 1.5, 
          bgcolor: (theme) => theme.palette.mode === 'dark' ? 'rgba(33, 150, 243, 0.15)' : '#e3f2fd',
          borderRadius: 1,
          border: '1px solid',
          borderColor: (theme) => theme.palette.mode === 'dark' ? 'rgba(33, 150, 243, 0.3)' : '#90caf9'
        }}>
          <Typography variant="body2" sx={{ fontSize: '12px' }}>
            💡 <strong>색상, 선 굵기, 선 유형</strong>을 수정하시면 차트에 즉시 반영됩니다
          </Typography>
        </Box>

        {/* 헤더 행 */}
        <Box sx={{ 
          display: 'grid', 
          gridTemplateColumns: '60px 120px 120px 90px 150px 1fr 100px',
          gap: 1,
          p: 1.5, 
          mb: 1, 
          bgcolor: (theme) => theme.palette.mode === 'dark' ? '#616161' : '#9e9e9e',
          borderRadius: 1,
        }}>
          <Typography variant="caption" fontWeight="bold" sx={{ textAlign: 'center', color: 'white' }}>ON/OFF</Typography>
          <Typography variant="caption" fontWeight="bold" sx={{ textAlign: 'center', color: 'white' }}>활성화</Typography>
          <Typography variant="caption" fontWeight="bold" sx={{ textAlign: 'center', color: 'white' }}>기준값</Typography>
          <Typography variant="caption" fontWeight="bold" sx={{ textAlign: 'center', color: 'white' }}>색상</Typography>
          <Typography variant="caption" fontWeight="bold" sx={{ textAlign: 'center', color: 'white' }}>굵기</Typography>
          <Typography variant="caption" fontWeight="bold" sx={{ textAlign: 'center', color: 'white' }}>선 유형</Typography>
          <Typography variant="caption" fontWeight="bold" sx={{ textAlign: 'center', color: 'white' }}>미리보기</Typography>
        </Box>

        {/* 각 MA 설정 행 */}
        {tempMALines.map((ma, index) => (
          <Box 
            key={ma.id}
            sx={{ 
              display: 'grid', 
              gridTemplateColumns: '60px 120px 120px 90px 150px 1fr 100px',
              gap: 1,
              p: 1.5, 
              mb: 1, 
              border: '1px solid',
              borderColor: 'divider',
              bgcolor: 'background.paper',
              borderRadius: 1,
              alignItems: 'center',
              transition: 'all 0.2s',
            }}
          >
            {/* 토글 스위치 */}
            <Box sx={{ display: 'flex', justifyContent: 'center' }}>
              <Switch
                checked={ma.enabled}
                onChange={() => handleToggle(index)}
                size="small"
              />
            </Box>

            {/* 이름 */}
            <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
              <Typography 
                variant="body2" 
                fontWeight={ma.enabled ? 'bold' : 'normal'}
                color={ma.enabled ? 'text.primary' : 'text.secondary'}
              >
                {ma.id}
              </Typography>
            </Box>

            {/* 기간 */}
            <TextField
              type="number"
              value={ma.period}
              onChange={(e) => handlePeriodChange(index, parseInt(e.target.value) || 1)}
              disabled={!ma.enabled}
              size="small"
              inputProps={{ min: 1, max: 1000 }}
              sx={{ 
                '& .MuiInputBase-input': { 
                  textAlign: 'center',
                  fontSize: '0.875rem',
                  padding: '6px 8px',
                }
              }}
            />

            {/* 색상 */}
            <Box sx={{ display: 'flex', justifyContent: 'center' }}>
              <Box
                sx={{
                  width: 40,
                  height: 40,
                  borderRadius: 1,
                  bgcolor: ma.color,
                  border: '2px solid',
                  borderColor: ma.enabled ? '#1976d2' : '#ccc',
                  cursor: ma.enabled ? 'pointer' : 'not-allowed',
                  opacity: ma.enabled ? 1 : 0.5,
                  position: 'relative',
                  '&:hover': ma.enabled ? { 
                    boxShadow: '0 0 8px rgba(25, 118, 210, 0.6)',
                    transform: 'scale(1.05)',
                  } : {},
                  transition: 'all 0.2s',
                }}
              >
                {ma.enabled && (
                  <input
                    type="color"
                    value={ma.color}
                    onChange={(e) => handleColorChange(index, e.target.value)}
                    style={{ 
                      position: 'absolute', 
                      top: 0, 
                      left: 0, 
                      width: '100%', 
                      height: '100%', 
                      opacity: 0, 
                      cursor: 'pointer',
                      border: 'none',
                    }}
                  />
                )}
              </Box>
            </Box>

            {/* 선 굵기 슬라이더 */}
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, px: 1 }}>
              <Slider
                value={ma.width}
                onChange={(_, value) => handleWidthChange(index, value as number)}
                disabled={!ma.enabled}
                min={0.5}
                max={5}
                step={0.5}
                sx={{ flex: 1 }}
              />
              <Typography variant="caption" sx={{ minWidth: 35, textAlign: 'right', fontSize: '11px' }}>
                {ma.width.toFixed(1)}px
              </Typography>
            </Box>

            {/* 선 유형 (고정) */}
            <Box sx={{ display: 'flex', justifyContent: 'center' }}>
              <Select
                value="실선"
                size="small"
                disabled
                sx={{ 
                  width: '100%',
                  '& .MuiSelect-select': { 
                    py: 0.5,
                    fontSize: '0.875rem',
                  }
                }}
              >
                <MenuItem value="실선">실선</MenuItem>
              </Select>
            </Box>

            {/* 미리보기 */}
            <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
              <Box
                sx={{
                  width: 60,
                  height: ma.width * 2 + 2,
                  maxHeight: 12,
                  backgroundColor: ma.enabled ? ma.color : '#ccc',
                  borderRadius: 0.5,
                }}
              />
            </Box>
          </Box>
        ))}

      </DialogContent>

    </Dialog>
  );
};

export default MASettingsDialog;

