import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Grid,
  TextField,
  Typography,
  Box,
  Divider,
  useTheme,
  useMediaQuery,
  IconButton,
} from '@mui/material';
import { Close } from '@mui/icons-material';
import { useChartColors, ChartColorSettings } from '../contexts/ChartColorContext';
import DraggablePaper from './DraggablePaper';

interface ChartColorSettingsDialogProps {
  open: boolean;
  onClose: () => void;
}

const ChartColorSettingsDialog: React.FC<ChartColorSettingsDialogProps> = ({ open, onClose }) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const { colors, updateColors, resetColors } = useChartColors();
  const [tempColors, setTempColors] = useState<ChartColorSettings>(colors);

  // 다이얼로그가 열릴 때마다 현재 색상으로 초기화
  React.useEffect(() => {
    if (open) {
      setTempColors(colors);
    }
  }, [open, colors]);

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

  const handleSave = () => {
    updateColors(tempColors);
    onClose();
  };

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

  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)}
            inputProps={{ style: { fontSize: isMobile ? '12px' : '14px' } }}
          />
        </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>
    );
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="sm"
      fullWidth
      fullScreen={isMobile}
      hideBackdrop={true}
      disableScrollLock={true}
      PaperComponent={DraggablePaper}
      sx={{
        pointerEvents: 'none',
        '& .MuiDialog-container': {
          pointerEvents: 'none',
          alignItems: 'flex-start',
        },
      }}
      PaperProps={{
        sx: {
          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',
        alignItems: 'center',
        justifyContent: 'space-between',
        bgcolor: '#1976d2',
        color: '#fff',
        py: 1.2,
      }}>
        <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '16px', color: '#fff' }}>
          📊 차트 색상 설정
        </Typography>
        <IconButton onClick={onClose} size="small" sx={{ color: '#fff' }}>
          <Close />
        </IconButton>
      </DialogTitle>
      <DialogContent dividers>
        {/* 캔들 색상 */}
        <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>
          <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 }} />

        {/* MACD 색상 */}
        <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 }} />

        {/* Stochastic 색상 */}
        <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>
      </DialogContent>
      <DialogActions sx={{ p: 2 }}>
        <Button onClick={handleReset} color="error" variant="outlined">
          초기화
        </Button>
        <Box sx={{ flex: 1 }} />
        <Button onClick={onClose} variant="outlined">
          취소
        </Button>
        <Button onClick={handleSave} variant="contained" color="primary">
          저장
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default ChartColorSettingsDialog;

