import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Checkbox,
  IconButton,
  Typography,
  Divider,
  Select,
  MenuItem,
  FormControl,
  FormControlLabel,
  Tabs,
  Tab,
} from '@mui/material';
import { Close as CloseIcon } from '@mui/icons-material';
import DraggablePaper from './DraggablePaper';

export interface MeasureSettings {
  lineColor: string;
  lineStyle: 'solid' | 'dashed' | 'dotted';
  lineWidth: number;
  backgroundColor: string;
  backgroundEnabled: boolean;
  backgroundOpacity: number;
  extendTop: boolean;
  extendBottom: boolean;
  labelColor: string;
  labelSize: number;
  labelBackgroundEnabled: boolean;
}

interface MeasureSettingsDialogProps {
  open: boolean;
  onClose: () => void;
  settings: MeasureSettings;
  onSave: (settings: MeasureSettings) => void;
  onDelete?: () => void;
  isEditingIndividual?: boolean;
}

export const defaultMeasureSettings: MeasureSettings = {
  lineColor: '#2962ff',
  lineStyle: 'solid',
  lineWidth: 2,
  backgroundColor: '#2962ff',
  backgroundEnabled: true,
  backgroundOpacity: 0.15,
  extendTop: false,
  extendBottom: false,
  labelColor: '#2962ff',
  labelSize: 12,
  labelBackgroundEnabled: true,
};

const MeasureSettingsDialog: React.FC<MeasureSettingsDialogProps> = ({
  open,
  onClose,
  settings,
  onSave,
  onDelete,
  isEditingIndividual = false,
}) => {
  const [localSettings, setLocalSettings] = useState<MeasureSettings>(settings);
  const [activeTab, setActiveTab] = useState(0);

  useEffect(() => {
    setLocalSettings(settings);
  }, [settings]);

  const handleChange = (field: keyof MeasureSettings, value: any) => {
    setLocalSettings(prev => ({ ...prev, [field]: value }));
  };

  const handleSave = () => {
    onSave(localSettings);
    onClose();
  };

  const handleReset = () => {
    setLocalSettings(defaultMeasureSettings);
  };

  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: {
          borderRadius: 2,
          bgcolor: 'background.paper',
          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,
        }}
      >
        <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '16px', color: '#fff' }}>
          기간 {isEditingIndividual ? '편집' : '설정'}
        </Typography>
        <IconButton onClick={onClose} size="small" sx={{ color: '#fff' }}>
          <CloseIcon />
        </IconButton>
      </DialogTitle>

      <Divider />

      <DialogContent sx={{ p: 0 }}>
        {/* 탭 */}
        <Tabs
          value={activeTab}
          onChange={(e, newValue) => setActiveTab(newValue)}
          sx={{ borderBottom: 1, borderColor: 'divider' }}
        >
          <Tab label="모습" />
          <Tab label="작표" />
          <Tab label="보임" />
        </Tabs>

        {/* 탭 내용 */}
        <Box sx={{ p: 3 }}>
          {/* 모습 탭 */}
          {activeTab === 0 && (
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
              {/* 라인 */}
              <Box>
                <Typography variant="subtitle2" gutterBottom fontWeight={600}>
                  라인
                </Typography>
                <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', mt: 1 }}>
                  <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
                    <input
                      type="color"
                      value={localSettings.lineColor}
                      onChange={(e) => handleChange('lineColor', e.target.value)}
                      style={{
                        width: 50,
                        height: 35,
                        border: '1px solid #ccc',
                        borderRadius: 4,
                        cursor: 'pointer',
                      }}
                    />
                    <Box
                      sx={{
                        width: 50,
                        height: 25,
                        bgcolor: localSettings.lineColor,
                        borderRadius: 0.5,
                        border: '1px solid rgba(0,0,0,0.2)',
                      }}
                    />
                  </Box>
                  
                  <FormControl size="small" sx={{ minWidth: 100 }}>
                    <Select
                      value={localSettings.lineStyle}
                      onChange={(e) => handleChange('lineStyle', e.target.value)}
                    >
                      <MenuItem value="solid">━━━</MenuItem>
                      <MenuItem value="dashed">- - -</MenuItem>
                      <MenuItem value="dotted">· · ·</MenuItem>
                    </Select>
                  </FormControl>
                  
                  <FormControl size="small" sx={{ minWidth: 80 }}>
                    <Select
                      value={localSettings.lineWidth}
                      onChange={(e) => handleChange('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>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={localSettings.backgroundEnabled}
                      onChange={(e) => handleChange('backgroundEnabled', e.target.checked)}
                    />
                  }
                  label={
                    <Typography variant="subtitle2" fontWeight={600}>
                      배경
                    </Typography>
                  }
                />
                {localSettings.backgroundEnabled && (
                  <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', mt: 1, ml: 4 }}>
                    <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
                      <input
                        type="color"
                        value={localSettings.backgroundColor}
                        onChange={(e) => handleChange('backgroundColor', e.target.value)}
                        style={{
                          width: 50,
                          height: 35,
                          border: '1px solid #ccc',
                          borderRadius: 4,
                          cursor: 'pointer',
                        }}
                      />
                      <Box
                        sx={{
                          width: 50,
                          height: 25,
                          bgcolor: localSettings.backgroundColor,
                          borderRadius: 0.5,
                          border: '1px solid rgba(0,0,0,0.2)',
                          opacity: localSettings.backgroundOpacity,
                        }}
                      />
                    </Box>
                    
                    <FormControl size="small" sx={{ minWidth: 100 }}>
                      <Select
                        value={Math.round(localSettings.backgroundOpacity * 100)}
                        onChange={(e) => handleChange('backgroundOpacity', Number(e.target.value) / 100)}
                      >
                        <MenuItem value={5}>5%</MenuItem>
                        <MenuItem value={10}>10%</MenuItem>
                        <MenuItem value={15}>15%</MenuItem>
                        <MenuItem value={20}>20%</MenuItem>
                        <MenuItem value={30}>30%</MenuItem>
                        <MenuItem value={50}>50%</MenuItem>
                      </Select>
                    </FormControl>
                  </Box>
                )}
              </Box>

              {/* 익스텐드 탭 */}
              <Box>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={localSettings.extendTop}
                      onChange={(e) => handleChange('extendTop', e.target.checked)}
                    />
                  }
                  label="익스텐드 탭"
                />
              </Box>

              {/* 익스텐드 바텀 */}
              <Box>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={localSettings.extendBottom}
                      onChange={(e) => handleChange('extendBottom', e.target.checked)}
                    />
                  }
                  label="익스텐드 바텀"
                />
              </Box>
            </Box>
          )}

          {/* 작표 탭 */}
          {activeTab === 1 && (
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
              {/* 라벨 */}
              <Box>
                <Typography variant="subtitle2" gutterBottom fontWeight={600}>
                  라벨
                </Typography>
                <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', mt: 1 }}>
                  <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
                    <input
                      type="color"
                      value={localSettings.labelColor}
                      onChange={(e) => handleChange('labelColor', e.target.value)}
                      style={{
                        width: 50,
                        height: 35,
                        border: '1px solid #ccc',
                        borderRadius: 4,
                        cursor: 'pointer',
                      }}
                    />
                    <Box
                      sx={{
                        width: 50,
                        height: 25,
                        bgcolor: localSettings.labelColor,
                        borderRadius: 0.5,
                        border: '1px solid rgba(0,0,0,0.2)',
                      }}
                    />
                  </Box>
                  
                  <FormControl size="small" sx={{ minWidth: 100 }}>
                    <Select
                      value={localSettings.labelSize}
                      onChange={(e) => handleChange('labelSize', Number(e.target.value))}
                    >
                      <MenuItem value={10}>10</MenuItem>
                      <MenuItem value={11}>11</MenuItem>
                      <MenuItem value={12}>12</MenuItem>
                      <MenuItem value={13}>13</MenuItem>
                      <MenuItem value={14}>14</MenuItem>
                      <MenuItem value={16}>16</MenuItem>
                      <MenuItem value={18}>18</MenuItem>
                    </Select>
                  </FormControl>
                </Box>
              </Box>

              {/* 라벨 배그라운드 */}
              <Box>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={localSettings.labelBackgroundEnabled}
                      onChange={(e) => handleChange('labelBackgroundEnabled', e.target.checked)}
                    />
                  }
                  label="라벨 백그라운드"
                />
              </Box>
            </Box>
          )}

          {/* 보임 탭 (비어있음) */}
          {activeTab === 2 && (
            <Box sx={{ p: 2, textAlign: 'center', color: 'text.secondary' }}>
              <Typography>추가 옵션이 없습니다.</Typography>
            </Box>
          )}
        </Box>
      </DialogContent>

      <Divider />

      <DialogActions sx={{ p: 2, gap: 1 }}>
        {isEditingIndividual && onDelete && (
          <Button 
            onClick={() => {
              if (window.confirm('이 기간 측정을 삭제하시겠습니까?')) {
                onDelete();
                onClose();
              }
            }} 
            variant="outlined" 
            color="error"
          >
            삭제
          </Button>
        )}
        <Button onClick={handleReset} variant="outlined" color="secondary">
          초기화
        </Button>
        <Box sx={{ flex: 1 }} />
        <Button onClick={onClose} variant="outlined">
          취소
        </Button>
        <Button onClick={handleSave} variant="contained" color="primary">
          확인
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default MeasureSettingsDialog;

