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

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

interface ExtendedSettings {
    extended?: boolean;
    showLabel?: boolean;
    customText?: string;
}

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

type DrawingStyle = NonNullable<DrawingObject['style']>;

const DrawingSettingsDialog: React.FC<DrawingSettingsDialogProps> = ({
    open,
    onClose,
    drawing,
    onSave,
    onDelete,
}) => {
    const [settings, setSettings] = useState<DrawingStyle>({
        color: '#2962ff',
        lineWidth: 2,
        lineStyle: 'solid',
        fillColor: 'rgba(41, 98, 255, 0.2)',
        fillOpacity: 0.2,
        fontSize: 14,
        text: '',
    });

    const [extendedSettings, setExtendedSettings] = useState<ExtendedSettings>({
        extended: false,
        showLabel: true,
        customText: '',
    });

    useEffect(() => {
        if (drawing && drawing.style) {
            setSettings({
                color: drawing.style.color,
                lineWidth: drawing.style.lineWidth,
                lineStyle: drawing.style.lineStyle,
                fillColor: drawing.style.fillColor || 'rgba(41, 98, 255, 0.2)',
                fillOpacity: drawing.style.fillOpacity || 0.2,
                fontSize: drawing.style.fontSize || 14,
                text: drawing.style.text || '',
            });
            setExtendedSettings({
                extended: drawing.extended || false,
                showLabel: drawing.showLabel !== false,
                customText: drawing.customText || '',
            });
        }
    }, [drawing]);

    if (!drawing) return null;

    const handleSave = () => {
        if (drawing) {
            onSave({
                ...drawing,
                style: settings,
                extended: extendedSettings.extended,
                showLabel: extendedSettings.showLabel,
                customText: extendedSettings.customText,
            });
            onClose();
        }
    };

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

    const isTextTool = drawing.type === 'text';
    const isFilledTool = drawing.type === 'rectangle' || drawing.type === 'brush'; // Brush technically not filled usually, but reusing logic

    return (
        <Dialog 
            open={open} 
            onClose={onClose} 
            maxWidth="xs" 
            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: '#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' }}>
                    <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={() => setSettings({ ...settings, color: c })}
                                    sx={{
                                        width: 24,
                                        height: 24,
                                        borderRadius: '50%',
                                        bgcolor: c,
                                        cursor: 'pointer',
                                        border: settings.color === c ? '2px solid #fff' : '1px solid #ddd',
                                        boxShadow: settings.color === c ? '0 0 0 2px #2962ff' : 'none',
                                    }}
                                />
                            ))}
                        </Box>
                    </Grid>

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

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

                    {/* Text Content & Size (Text Tool Only) */}
                    {isTextTool && (
                        <>
                            <Grid item xs={12}>
                                <TextField
                                    fullWidth
                                    label="텍스트 내용"
                                    value={settings.text}
                                    onChange={(e) => setSettings({ ...settings, text: e.target.value })}
                                />
                            </Grid>
                            <Grid item xs={12}>
                                <Typography variant="subtitle2" gutterBottom>폰트 크기: {settings.fontSize}px</Typography>
                                <Slider
                                    value={settings.fontSize}
                                    min={10}
                                    max={40}
                                    step={1}
                                    onChange={(_, val) => setSettings({ ...settings, fontSize: val as number })}
                                />
                            </Grid>
                        </>
                    )}

                    {/* Fill Settings (Rectangle Only) */}
                    {drawing.type === 'rectangle' && (
                        <Grid item xs={12}>
                            <Typography variant="subtitle2" gutterBottom>배경 불투명도: {(settings.fillOpacity! * 100).toFixed(0)}%</Typography>
                            <Slider
                                value={settings.fillOpacity}
                                min={0}
                                max={1}
                                step={0.1}
                                onChange={(_, val) => setSettings({ ...settings, fillOpacity: val as number })}
                            />
                        </Grid>
                    )}

                    {/* Extended Options (for lines that can extend) */}
                    {(drawing.type === 'trendLine' || drawing.type === 'diagonalLine' || drawing.type === 'angleLine' || drawing.type === 'horizontalLine') && (
                        <Grid item xs={12}>
                            <FormControlLabel
                                control={
                                    <Switch
                                        checked={extendedSettings.extended}
                                        onChange={(e) => setExtendedSettings({ ...extendedSettings, extended: e.target.checked })}
                                    />
                                }
                                label="보조지표 영역까지 확장"
                            />
                        </Grid>
                    )}

                    {/* Label Options */}
                    {(drawing.type === 'trendLine' || drawing.type === 'diagonalLine' || drawing.type === 'angleLine' || drawing.type === 'horizontalLine') && (
                        <>
                            <Grid item xs={12}>
                                <FormControlLabel
                                    control={
                                        <Switch
                                            checked={extendedSettings.showLabel}
                                            onChange={(e) => setExtendedSettings({ ...extendedSettings, showLabel: e.target.checked })}
                                        />
                                    }
                                    label="라벨 표시"
                                />
                            </Grid>
                            <Grid item xs={12}>
                                <TextField
                                    fullWidth
                                    size="small"
                                    label="커스텀 텍스트 (선택사항)"
                                    value={extendedSettings.customText}
                                    onChange={(e) => setExtendedSettings({ ...extendedSettings, customText: e.target.value })}
                                    placeholder="예: 저항선, 지지선"
                                />
                            </Grid>
                        </>
                    )}

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

export default DrawingSettingsDialog;
