import React, { useState, useEffect, useRef } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  Button,
  Box,
  TextField,
  Checkbox,
  Typography,
  Divider,
  Select,
  MenuItem,
  FormControl,
  Tabs,
  Tab,
  Slider,
  Popover,
} from '@mui/material';
import { Edit as EditIcon } from '@mui/icons-material';
import DraggablePaper from './DraggablePaper';

export interface FibonacciLevel {
  value: number;
  enabled: boolean;
  color: string;
  lineStyle: 'solid' | 'dashed' | 'dotted';
  lineWidth: number;
  opacity?: number; // 투명도 (0-100)
}

export interface FibonacciBaseline {
  color: string;
  lineStyle: 'solid' | 'dashed' | 'dotted';
  lineWidth: number;
}

export interface FibonacciTimezoneSettings {
  baseline: FibonacciBaseline;  // ✅ 기준선 설정 추가
  levels: FibonacciLevel[];
  showAcrossIndicators?: boolean; // ✅ 보조지표까지 보기
}

interface FibonacciTimezoneDialogProps {
  open: boolean;
  onClose: () => void;
  settings: FibonacciTimezoneSettings;
  onSave: (settings: FibonacciTimezoneSettings) => void;
  onDelete?: () => void; // ✅ 삭제 콜백 (개별 피보나치 편집 시에만 사용)
  isEditingIndividual?: boolean; // ✅ 개별 피보나치 편집 여부
}

const defaultBaseline: FibonacciBaseline = {
  color: '#808080',
  lineStyle: 'solid',
  lineWidth: 2,
};

const defaultLevels: FibonacciLevel[] = [
  { value: 5, enabled: true, color: '#2196F3', lineStyle: 'solid', lineWidth: 1, opacity: 100 },
  { value: 8, enabled: true, color: '#2196F3', lineStyle: 'solid', lineWidth: 1, opacity: 100 },
  { value: 7, enabled: true, color: '#2196F3', lineStyle: 'solid', lineWidth: 1, opacity: 100 },
  { value: 11, enabled: true, color: '#FF5252', lineStyle: 'solid', lineWidth: 1, opacity: 100 },
  { value: 15, enabled: true, color: '#2196F3', lineStyle: 'solid', lineWidth: 1, opacity: 100 },
  { value: 13, enabled: true, color: '#2196F3', lineStyle: 'solid', lineWidth: 1, opacity: 100 },
  { value: 21, enabled: true, color: '#2196F3', lineStyle: 'solid', lineWidth: 1, opacity: 100 },
  { value: 34, enabled: true, color: '#2196F3', lineStyle: 'solid', lineWidth: 1, opacity: 100 },
  { value: 55, enabled: true, color: '#2196F3', lineStyle: 'solid', lineWidth: 1, opacity: 100 },
  { value: 89, enabled: true, color: '#2196F3', lineStyle: 'solid', lineWidth: 1, opacity: 100 },
];

const FibonacciTimezoneDialog: React.FC<FibonacciTimezoneDialogProps> = ({
  open,
  onClose,
  settings,
  onSave,
  onDelete,
  isEditingIndividual = false,
}) => {
  const [localSettings, setLocalSettings] = useState<FibonacciTimezoneSettings>(() => ({
    baseline: settings.baseline || defaultBaseline,
    levels: settings.levels || defaultLevels,
  }));
  const [currentTab, setCurrentTab] = useState(0); // 0: 모습, 1: 좌표, 2: 보임
  const [showBackground, setShowBackground] = useState(false);
  const [showLabels, setShowLabels] = useState(true);
  const [colorPickerAnchor, setColorPickerAnchor] = useState<{ el: HTMLElement; index: number; isBaseline: boolean } | null>(null);

  useEffect(() => {
    // ✅ baseline이 없으면 기본값 추가 (기존 저장된 데이터 호환)
    setLocalSettings({
      baseline: settings.baseline || defaultBaseline,
      levels: settings.levels || defaultLevels,
      showAcrossIndicators: settings.showAcrossIndicators || false,
    });
  }, [settings]);

  const handleBaselineChange = (field: keyof FibonacciBaseline, value: any) => {
    setLocalSettings({
      ...localSettings,
      baseline: { ...(localSettings.baseline || defaultBaseline), [field]: value },
    });
  };

  const handleLevelChange = (index: number, field: keyof FibonacciLevel, value: any) => {
    const newLevels = [...localSettings.levels];
    newLevels[index] = { ...newLevels[index], [field]: value };
    setLocalSettings({ ...localSettings, levels: newLevels });
  };

  const handleSave = () => {
    // ✅ baseline이 없으면 기본값 추가
    const settingsToSave: FibonacciTimezoneSettings = {
      baseline: localSettings.baseline || defaultBaseline,
      levels: localSettings.levels,
      showAcrossIndicators: localSettings.showAcrossIndicators || false,
    };
    onSave(settingsToSave);
    onClose();
  };

  const handleReset = () => {
    setLocalSettings({ baseline: defaultBaseline, levels: defaultLevels });
  };

  // 색상 팔레트
  const colorPalette = [
    ['#000000', '#434651', '#666666', '#999999', '#B2B5BE', '#D1D4DC', '#E1E3EB', '#F0F3FA'],
    ['#F23645', '#FF9800', '#FDD835', '#26A69A', '#00BCD4', '#2196F3', '#3F51B5', '#9C27B0'],
    ['#880E4F', '#B71C1C', '#E65100', '#F57F17', '#827717', '#33691E', '#1B5E20', '#004D40'],
    ['#FF5252', '#FF6E40', '#FFAB40', '#FFD740', '#AEEA00', '#69F0AE', '#40C4FF', '#448AFF'],
    ['#FF80AB', '#FF4081', '#F50057', '#C51162', '#880E4F', '#4A148C', '#311B92', '#1A237E'],
    ['#EA80FC', '#E040FB', '#D500F9', '#AA00FF', '#6200EA', '#304FFE', '#2962FF', '#0091EA'],
    ['#8C9EFF', '#536DFE', '#3D5AFE', '#1976D2', '#0277BD', '#006064', '#004D40', '#1B5E20'],
  ];

  const handleColorPickerOpen = (event: React.MouseEvent<HTMLElement>, index: number, isBaseline: boolean) => {
    setColorPickerAnchor({ el: event.currentTarget, index, isBaseline });
  };

  const handleColorPickerClose = () => {
    setColorPickerAnchor(null);
  };

  const handleColorSelect = (color: string) => {
    if (colorPickerAnchor) {
      if (colorPickerAnchor.isBaseline) {
        handleBaselineChange('color', color);
      } else {
        handleLevelChange(colorPickerAnchor.index, 'color', color);
      }
    }
  };

  const handleShowAcrossIndicatorsChange = (checked: boolean) => {
    setLocalSettings({ ...localSettings, showAcrossIndicators: checked });
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="sm"
      fullWidth
      hideBackdrop={true}
      disableScrollLock={true}
      PaperComponent={DraggablePaper}
      sx={{
        pointerEvents: 'none',
        '& .MuiDialog-container': {
          pointerEvents: 'none',
          alignItems: 'flex-start',
        },
      }}
      PaperProps={{
        sx: {
          bgcolor: 'background.paper',
          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', 
        alignItems: 'center', 
        justifyContent: 'space-between',
        bgcolor: '#1976d2',
        color: '#fff',
        py: 1.2,
      }}>
        <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '16px', color: '#fff' }}>
          피보나치 타임존
        </Typography>
        <Box sx={{ display: 'flex', gap: 1 }}>
          <Button 
            onClick={onClose} 
            variant="outlined" 
            size="small"
            sx={{ 
              color: '#fff', 
              borderColor: 'rgba(255,255,255,0.5)',
              '&:hover': {
                borderColor: '#fff',
                bgcolor: 'rgba(255,255,255,0.1)',
              }
            }}
          >
            취소
          </Button>
          <Button 
            onClick={handleSave} 
            variant="contained"
            size="small"
            sx={{ 
              bgcolor: '#fff',
              color: '#1976d2',
              '&:hover': {
                bgcolor: 'rgba(255,255,255,0.9)',
              }
            }}
          >
            확인
          </Button>
        </Box>
      </DialogTitle>

      <Divider />

      {/* 탭 */}
      <Tabs
        value={currentTab}
        onChange={(e, newValue) => setCurrentTab(newValue)}
        sx={{ borderBottom: 1, borderColor: 'divider', px: 2 }}
      >
        <Tab label="모습" />
        <Tab label="좌표" />
        <Tab label="보임" />
      </Tabs>

      <DialogContent sx={{ pt: 2 }}>
        {/* 모습 탭 */}
        {currentTab === 0 && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {/* 기준선 설정 */}
            <Box>
              <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 'bold' }}>
                기준선 (항상 표시)
              </Typography>
            <Box
              sx={{
                display: 'grid',
                gridTemplateColumns: '50px 80px 100px 80px 80px',
                gap: 1,
                alignItems: 'center',
                bgcolor: 'action.hover',
                p: 1,
                borderRadius: 1,
              }}
            >
              <Checkbox
                checked={true}
                disabled={true}
                size="small"
                sx={{ justifySelf: 'center' }}
              />
              <TextField
                value="0"
                disabled={true}
                size="small"
                type="number"
              />
              <Box
                onClick={(e) => handleColorPickerOpen(e, 0, true)}
                sx={{
                  width: 60,
                  height: 30,
                  bgcolor: (localSettings.baseline || defaultBaseline).color,
                  borderRadius: 1,
                  border: '2px solid',
                  borderColor: 'primary.main',
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  '&:hover': {
                    opacity: 0.8,
                  },
                }}
              >
                <EditIcon sx={{ fontSize: 16, color: 'white', textShadow: '0 0 2px black' }} />
              </Box>
              <FormControl size="small" fullWidth>
                <Select
                  value={(localSettings.baseline || defaultBaseline).lineStyle}
                  onChange={(e) => handleBaselineChange('lineStyle', e.target.value)}
                >
                  <MenuItem value="solid">━━━</MenuItem>
                  <MenuItem value="dashed">- - -</MenuItem>
                  <MenuItem value="dotted">· · ·</MenuItem>
                </Select>
              </FormControl>
              <FormControl size="small" fullWidth>
                <Select
                  value={(localSettings.baseline || defaultBaseline).lineWidth}
                  onChange={(e) => handleBaselineChange('lineWidth', Number(e.target.value))}
                >
                  <MenuItem value={1}>1</MenuItem>
                  <MenuItem value={2}>2</MenuItem>
                  <MenuItem value={3}>3</MenuItem>
                  <MenuItem value={4}>4</MenuItem>
                </Select>
              </FormControl>
            </Box>
          </Box>

          {/* 레벨 설정 */}
          <Box>
            <Box sx={{ display: 'grid', gridTemplateColumns: '50px 80px 100px 80px 80px', gap: 1, mb: 1 }}>
              <Typography variant="caption" sx={{ fontWeight: 'bold', textAlign: 'center' }}>
                표시
              </Typography>
              <Typography variant="caption" sx={{ fontWeight: 'bold' }}>
                값
              </Typography>
              <Typography variant="caption" sx={{ fontWeight: 'bold' }}>
                색상
              </Typography>
              <Typography variant="caption" sx={{ fontWeight: 'bold' }}>
                스타일
              </Typography>
              <Typography variant="caption" sx={{ fontWeight: 'bold' }}>
                두께
              </Typography>
            </Box>

            {localSettings.levels.map((level, index) => (
              <Box
                key={index}
                sx={{
                  display: 'grid',
                  gridTemplateColumns: '50px 80px 100px 80px 80px',
                  gap: 1,
                  alignItems: 'center',
                  mb: 0.5,
                }}
              >
                <Checkbox
                  checked={level.enabled}
                  onChange={(e) => handleLevelChange(index, 'enabled', e.target.checked)}
                  size="small"
                  sx={{ justifySelf: 'center' }}
                />
                <TextField
                  value={level.value}
                  onChange={(e) => handleLevelChange(index, 'value', Number(e.target.value))}
                  size="small"
                  type="number"
                  inputProps={{ min: 0 }}
                />
                <Box
                  onClick={(e) => handleColorPickerOpen(e, index, false)}
                  sx={{
                    width: 60,
                    height: 30,
                    bgcolor: level.color,
                    borderRadius: 1,
                    border: '2px solid',
                    borderColor: 'primary.main',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    '&:hover': {
                      opacity: 0.8,
                    },
                  }}
                >
                  <EditIcon sx={{ fontSize: 16, color: 'white', textShadow: '0 0 2px black' }} />
                </Box>
                <FormControl size="small" fullWidth>
                  <Select
                    value={level.lineStyle}
                    onChange={(e) => handleLevelChange(index, 'lineStyle', e.target.value)}
                  >
                    <MenuItem value="solid">━━━</MenuItem>
                    <MenuItem value="dashed">- - -</MenuItem>
                    <MenuItem value="dotted">· · ·</MenuItem>
                  </Select>
                </FormControl>
                <FormControl size="small" fullWidth>
                  <Select
                    value={level.lineWidth}
                    onChange={(e) => handleLevelChange(index, 'lineWidth', Number(e.target.value))}
                  >
                    <MenuItem value={1}>1</MenuItem>
                    <MenuItem value={2}>2</MenuItem>
                    <MenuItem value={3}>3</MenuItem>
                    <MenuItem value={4}>4</MenuItem>
                  </Select>
                </FormControl>
              </Box>
            ))}
          </Box>

          {/* 보조지표까지 보기 + 삭제/초기화 버튼 */}
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mt: 2, p: 1.5, bgcolor: 'action.hover', borderRadius: 1 }}>
            <Checkbox
              checked={localSettings.showAcrossIndicators || false}
              onChange={(e) => handleShowAcrossIndicatorsChange(e.target.checked)}
              size="small"
            />
            <Typography variant="body2" sx={{ fontWeight: 'medium' }}>보조지표까지 보기</Typography>
            <Box sx={{ flex: 1 }} />
            {isEditingIndividual && onDelete && (
              <Button 
                onClick={() => {
                  if (window.confirm('이 피보나치 타임존을 삭제하시겠습니까?')) {
                    onDelete();
                    onClose();
                  }
                }} 
                variant="outlined" 
                color="error"
                size="small"
              >
                삭제
              </Button>
            )}
            <Button 
              onClick={handleReset} 
              variant="outlined" 
              color="secondary"
              size="small"
            >
              초기화
            </Button>
          </Box>
        </Box>
        )}

        {/* 좌표 탭 */}
        {currentTab === 1 && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <Typography variant="body2" color="text.secondary">
              좌표 설정은 드래그로 조정할 수 있습니다.
            </Typography>
          </Box>
        )}

        {/* 보임 탭 */}
        {currentTab === 2 && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <Checkbox
                checked={showBackground}
                onChange={(e) => setShowBackground(e.target.checked)}
                size="small"
              />
              <Typography variant="body2">배경</Typography>
            </Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <Checkbox
                checked={showLabels}
                onChange={(e) => setShowLabels(e.target.checked)}
                size="small"
              />
              <Typography variant="body2">라벨</Typography>
            </Box>
          </Box>
        )}

        {/* 색상 팔레트 팝오버 */}
        <Popover
          open={Boolean(colorPickerAnchor)}
          anchorEl={colorPickerAnchor?.el}
          onClose={handleColorPickerClose}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'left',
          }}
        >
          <Box sx={{ p: 2, width: 240 }}>
            {/* 색상 팔레트 */}
            {colorPalette.map((row, rowIndex) => (
              <Box key={rowIndex} sx={{ display: 'flex', gap: 0.5, mb: 0.5 }}>
                {row.map((color, colIndex) => (
                  <Box
                    key={colIndex}
                    onClick={() => {
                      handleColorSelect(color);
                      handleColorPickerClose();
                    }}
                    sx={{
                      width: 24,
                      height: 24,
                      bgcolor: color,
                      cursor: 'pointer',
                      border: '1px solid rgba(0,0,0,0.1)',
                      '&:hover': {
                        border: '2px solid white',
                        boxShadow: '0 0 4px rgba(0,0,0,0.3)',
                      },
                    }}
                  />
                ))}
              </Box>
            ))}

            {/* 투명도 슬라이더 */}
            <Box sx={{ mt: 2 }}>
              <Typography variant="caption" gutterBottom>
                투명도
              </Typography>
              <Slider
                value={colorPickerAnchor?.isBaseline 
                  ? 100 
                  : (localSettings.levels[colorPickerAnchor?.index || 0]?.opacity || 100)
                }
                onChange={(e, value) => {
                  if (colorPickerAnchor && !colorPickerAnchor.isBaseline) {
                    handleLevelChange(colorPickerAnchor.index, 'opacity', value as number);
                  }
                }}
                min={0}
                max={100}
                valueLabelDisplay="auto"
                valueLabelFormat={(value) => `${value}%`}
                sx={{ width: '100%' }}
              />
            </Box>

            {/* 커스텀 색상 입력 */}
            <Box sx={{ mt: 2, display: 'flex', gap: 1, alignItems: 'center' }}>
              <Typography variant="caption">색상 코드:</Typography>
              <input
                type="text"
                placeholder="#000000"
                onChange={(e) => {
                  const color = e.target.value;
                  if (/^#[0-9A-F]{6}$/i.test(color)) {
                    handleColorSelect(color);
                  }
                }}
                style={{
                  flex: 1,
                  padding: '4px 8px',
                  border: '1px solid #ccc',
                  borderRadius: '4px',
                  fontSize: '12px',
                }}
              />
            </Box>
          </Box>
        </Popover>
      </DialogContent>
    </Dialog>
  );
};

export default FibonacciTimezoneDialog;
export { defaultBaseline, defaultLevels };

