import React, { useState, useEffect } from 'react';
import {
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    Button,
    Grid,
    Typography,
    FormControl,
    InputLabel,
    Select,
    MenuItem,
    TextField,
    Box,
    IconButton,
    Slider,
    Switch,
    FormControlLabel,
    Chip,
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import AddIcon from '@mui/icons-material/Add';
import DeleteIcon from '@mui/icons-material/Delete';
import { DrawingObject } from './ChartDrawingOverlay';
import DraggablePaper from './DraggablePaper';

interface FibonacciDrawingSettingsDialogProps {
    open: boolean;
    onClose: () => void;
    drawing: DrawingObject | null;
    onSave: (updatedDrawing: DrawingObject) => void;
    onDelete: (drawingId: string) => void;
}

const colors = [
    '#2962ff', // Blue (Default)
    '#f44336', // Red
    '#4caf50', // Green
    '#ff9800', // Orange
    '#9c27b0', // Purple
    '#00bcd4', // Cyan
    '#ffffff', // White
    '#ffeb3b', // Yellow
];

const defaultFibLevels = [0.236, 0.382, 0.5, 0.618, 0.786, 1.0];

const FibonacciDrawingSettingsDialog: React.FC<FibonacciDrawingSettingsDialogProps> = ({
    open,
    onClose,
    drawing,
    onSave,
    onDelete,
}) => {
    const [color, setColor] = useState('#2962ff');
    const [lineWidth, setLineWidth] = useState(2);
    const [lineStyle, setLineStyle] = useState<'solid' | 'dashed' | 'dotted'>('solid');
    const [fillOpacity, setFillOpacity] = useState(0.1);
    const [fibLevels, setFibLevels] = useState<number[]>(defaultFibLevels);
    const [newLevel, setNewLevel] = useState('');

    useEffect(() => {
        if (drawing && drawing.style) {
            setColor(drawing.style.color);
            setLineWidth(drawing.style.lineWidth);
            setLineStyle(drawing.style.lineStyle);
            setFillOpacity(drawing.style.fillOpacity || 0.1);
            setFibLevels(drawing.fibLevels || defaultFibLevels);
        }
    }, [drawing]);

    if (!drawing) return null;

    const handleSave = () => {
        if (drawing) {
            onSave({
                ...drawing,
                style: {
                    ...drawing.style,
                    color,
                    lineWidth,
                    lineStyle,
                    fillOpacity,
                },
                fibLevels,
            });
            onClose();
        }
    };

    const handleDelete = () => {
        if (drawing) {
            onDelete(drawing.id);
            onClose();
        }
    };

    const handleAddLevel = () => {
        const level = parseFloat(newLevel);
        if (!isNaN(level) && level >= 0 && level <= 2) {
            setFibLevels([...fibLevels, level].sort((a, b) => a - b));
            setNewLevel('');
        }
    };

    const handleRemoveLevel = (index: number) => {
        setFibLevels(fibLevels.filter((_, i) => i !== index));
    };

    const handleResetLevels = () => {
        setFibLevels(defaultFibLevels);
    };

    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: {
                    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: '#9c27b0',
                color: '#fff',
                py: 1.2,
            }}>
                <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '16px', color: '#fff' }}>
                    피보나치 설정 - {drawing.type === 'fibonacciFan' ? '팬' : drawing.type === 'fibonacciCircle' ? '서클' : '웻지'}
                </Typography>
                <IconButton onClick={onClose} size="small" sx={{ color: '#fff' }}>
                    <CloseIcon />
                </IconButton>
            </DialogTitle>
            <DialogContent dividers>
                <Grid container spacing={2}>
                    {/* Line Color */}
                    <Grid item xs={12}>
                        <Typography variant="subtitle2" gutterBottom>선 색상</Typography>
                        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
                            {colors.map((c) => (
                                <Box
                                    key={c}
                                    onClick={() => setColor(c)}
                                    sx={{
                                        width: 28,
                                        height: 28,
                                        borderRadius: '50%',
                                        bgcolor: c,
                                        cursor: 'pointer',
                                        border: color === c ? '3px solid #fff' : '1px solid #ddd',
                                        boxShadow: color === c ? '0 0 0 2px #9c27b0' : 'none',
                                    }}
                                />
                            ))}
                        </Box>
                    </Grid>

                    {/* Line Width */}
                    <Grid item xs={12}>
                        <Typography variant="subtitle2" gutterBottom>선 굵기: {lineWidth}px</Typography>
                        <Slider
                            value={lineWidth}
                            min={1}
                            max={10}
                            step={1}
                            onChange={(_, val) => setLineWidth(val as number)}
                        />
                    </Grid>

                    {/* Line Style */}
                    <Grid item xs={12}>
                        <FormControl fullWidth size="small">
                            <InputLabel>선 스타일</InputLabel>
                            <Select
                                value={lineStyle}
                                label="선 스타일"
                                onChange={(e) => setLineStyle(e.target.value as any)}
                            >
                                <MenuItem value="solid">실선</MenuItem>
                                <MenuItem value="dashed">파선</MenuItem>
                                <MenuItem value="dotted">점선</MenuItem>
                            </Select>
                        </FormControl>
                    </Grid>

                    {/* Fill Opacity (Circle and Wedge) */}
                    {(drawing.type === 'fibonacciCircle' || drawing.type === 'fibonacciWedge') && (
                        <Grid item xs={12}>
                            <Typography variant="subtitle2" gutterBottom>채우기 불투명도: {(fillOpacity * 100).toFixed(0)}%</Typography>
                            <Slider
                                value={fillOpacity}
                                min={0}
                                max={0.5}
                                step={0.05}
                                onChange={(_, val) => setFillOpacity(val as number)}
                            />
                        </Grid>
                    )}

                    {/* Fibonacci Levels */}
                    <Grid item xs={12}>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
                            <Typography variant="subtitle2">피보나치 레벨</Typography>
                            <Button size="small" onClick={handleResetLevels} variant="outlined">
                                기본값 복원
                            </Button>
                        </Box>
                        <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap', mb: 1 }}>
                            {fibLevels.map((level, idx) => (
                                <Chip
                                    key={idx}
                                    label={`${(level * 100).toFixed(1)}%`}
                                    onDelete={() => handleRemoveLevel(idx)}
                                    size="small"
                                    color="primary"
                                    variant="outlined"
                                />
                            ))}
                        </Box>
                        <Box sx={{ display: 'flex', gap: 1 }}>
                            <TextField
                                size="small"
                                label="새 레벨 추가"
                                value={newLevel}
                                onChange={(e) => setNewLevel(e.target.value)}
                                placeholder="0.5 (50%)"
                                sx={{ flex: 1 }}
                            />
                            <Button 
                                variant="contained" 
                                onClick={handleAddLevel}
                                startIcon={<AddIcon />}
                            >
                                추가
                            </Button>
                        </Box>
                        <Typography variant="caption" color="text.secondary" sx={{ mt: 0.5, display: 'block' }}>
                            0.0 ~ 2.0 사이의 값 입력 (예: 0.5 = 50%, 1.618 = 161.8%)
                        </Typography>
                    </Grid>

                </Grid>
            </DialogContent>
            <DialogActions sx={{ justifyContent: 'space-between', px: 3, py: 2 }}>
                <Button onClick={handleDelete} color="error" variant="outlined" startIcon={<DeleteIcon />}>
                    삭제
                </Button>
                <Box>
                    <Button onClick={onClose} sx={{ mr: 1 }}>
                        취소
                    </Button>
                    <Button onClick={handleSave} variant="contained" sx={{ bgcolor: '#9c27b0', '&:hover': { bgcolor: '#7b1fa2' } }}>
                        확인
                    </Button>
                </Box>
            </DialogActions>
        </Dialog>
    );
};

export default FibonacciDrawingSettingsDialog;
