import React, { useState, useCallback, useEffect } from 'react';
import Cropper from 'react-easy-crop';
import { Modal, Button, Typography, Grid, Slider, Stack, ButtonGroup, FormControl, Paper } from '@mui/material';
import ZoomOutIcon from '@mui/icons-material/ZoomOut';
import ZoomInIcon from '@mui/icons-material/ZoomIn';
import RotateLeftIcon from '@mui/icons-material/RotateLeft';
import RotateRightIcon from '@mui/icons-material/RotateRight';
import { Area } from 'react-easy-crop';
import { getCroppedImg } from './cropImage';

const aspectRatios = [
    { value: 4 / 3, label: '4:3' },
    { value: 16 / 9, label: '16:9' },
    { value: 1, label: '1:1' },
    { value: 3 / 2, label: '3:2' },
    { value: undefined, label: 'Free' },
];

type ImageCropProps = {
    editedImage: File | null;
    setEditedImage: (file: File | null) => void;
    imageToEdit?: string;
};

const ImageCrop: React.FC<ImageCropProps> = ({ editedImage, setEditedImage, imageToEdit }) => {
    const [open, setOpen] = useState(false);
    const [crop, setCrop] = useState({ x: 0, y: 0 });
    const [zoom, setZoom] = useState(1);
    const [rotation, setRotation] = useState(0);
    const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);
    const [imageUrl, setImageUrl] = useState(imageToEdit || '');
    const [aspectRatio, setAspectRatio] = useState<number | undefined>(4 / 3);
    const [originalAspectRatio, setOriginalAspectRatio] = useState<number | undefined>(undefined);
    const [uploadedImage, setUploadedImage] = useState<string | null>(null);

    const handleOpen = () => setOpen(true);
    const handleClose = () => setOpen(false);

    const onCropComplete = useCallback((croppedArea: Area, croppedAreaPixels: Area) => {
        setCroppedAreaPixels(croppedAreaPixels);
    }, []);

    const handleSave = useCallback(async () => {
        if (croppedAreaPixels && imageUrl) {
            try {
                const croppedImage = await getCroppedImg(imageUrl, croppedAreaPixels, rotation);
                if (croppedImage) {
                    const file = new File([croppedImage], 'editedImage.png', { type: 'image/png' });
                    setEditedImage(file);
                    handleClose();
                }
            } catch (e) {
                console.error(e);
            }
        }
    }, [croppedAreaPixels, rotation, imageUrl, handleClose]);

    const handleAspectRatioChange = (newRatio: number | undefined) => {
        setAspectRatio(newRatio);
    };

    const handleZoomChange = (value: number) => {
        setZoom(Math.min(Math.max(value, 1), 3));
    };

    const handleRotationChange = (value: number) => {
        setRotation(((value % 360) + 360) % 360);
    };

    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = () => {
                setUploadedImage(reader.result as string);
                setImageUrl(reader.result as string);

                const img = new Image();
                img.src = reader.result as string;
                img.onload = () => {
                    setOriginalAspectRatio(img.width / img.height);
                };
            };
            reader.readAsDataURL(file);
        }
    };

    useEffect(() => {
        if (imageToEdit) {
            setImageUrl(imageToEdit);
        }
    }, [imageToEdit]);

    return (
        <Paper sx={{ display: 'flex', position: 'relative', justifyContent: 'center', alignItems: 'center', height: 200 , overflow: 'hidden' }}>
            <Button sx={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }} variant="contained" color="primary" onClick={handleOpen}>
                {editedImage ? 'Changer Image' : 'Sélectionner une image'}
            </Button>
            <Modal open={open} onClose={handleClose}>
                <Grid container justifyContent="center" alignItems="center" style={{ width: '65%', maxWidth: '70%', position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', backgroundColor: 'white', padding: '20px', borderRadius: '15px' }}>
                    <Grid item xs={12} sx={{ mb: 3 }}>
                        <Typography variant="h5" align="center" gutterBottom>
                            Modifier image
                        </Typography>
                    </Grid>
                    <Grid item xs={12} style={{ height: 400, position: 'relative' }}>
                        {imageUrl && (
                            <Cropper
                                image={imageUrl}
                                crop={crop}
                                zoom={zoom}
                                rotation={rotation}
                                aspect={aspectRatio}
                                cropShape="rect"
                                showGrid={false}
                                onCropChange={setCrop}
                                onZoomChange={setZoom}
                                onRotationChange={setRotation}
                                onCropComplete={onCropComplete}
                            />
                        )}
                    </Grid>
                    <Grid item xs={12} style={{ marginTop: '20px' }}>
                        <Stack spacing={2}>
                            <FormControl fullWidth>
                                <ButtonGroup variant="outlined" aria-label="outlined button group">
                                    {aspectRatios.map((ratio) => (
                                        <Button
                                            key={ratio.label}
                                            onClick={() => handleAspectRatioChange(ratio.value)}
                                            variant={aspectRatio === ratio.value ? 'contained' : 'outlined'}
                                        >
                                            {ratio.label}
                                        </Button>
                                    ))}
                                    {originalAspectRatio && (
                                        <Button
                                            onClick={() => handleAspectRatioChange(originalAspectRatio)}
                                            variant={aspectRatio === originalAspectRatio ? 'contained' : 'outlined'}
                                        >
                                            Original ({originalAspectRatio.toFixed(2)})
                                        </Button>
                                    )}
                                </ButtonGroup>
                            </FormControl>
                            <Stack direction="row" alignItems="center" spacing={2}>
                                <Button variant="outlined" color="success" onClick={() => handleZoomChange(zoom - 0.1)} disabled={zoom <= 1}><ZoomOutIcon /></Button>
                                <Slider value={zoom} min={1} max={3} step={0.1} onChange={(e, value) => handleZoomChange(value as number)} />
                                <Button variant="outlined" color="success" onClick={() => handleZoomChange(zoom + 0.1)} disabled={zoom >= 3}><ZoomInIcon /></Button>
                            </Stack>
                            <Stack direction="row" alignItems="center" spacing={2}>
                                <Button variant="outlined" color="success" onClick={() => handleRotationChange(rotation - 10)} disabled={rotation <= 0}><RotateLeftIcon /></Button>
                                <Slider value={rotation} min={0} max={360} step={1} onChange={(e, value) => handleRotationChange(value as number)} />
                                <Button variant="outlined" color="success" onClick={() => handleRotationChange(rotation + 10)} disabled={rotation >= 360}><RotateRightIcon /></Button>
                            </Stack>
                            <input
                                accept="image/*"
                                type="file"
                                onChange={handleFileChange}
                                style={{ display: 'none' }}
                                id="file-upload"
                            />
                            <label htmlFor="file-upload">
                                <Button variant="outlined" component="span">
                                    Ajouter nouvelle image
                                </Button>
                            </label>
                        </Stack>
                    </Grid>
                    <Grid item xs={12} style={{ marginTop: '20px' }}>
                        <Grid container justifyContent="center">
                            <Button variant="outlined" onClick={handleClose} style={{ marginRight: '10px' }}>Cancel</Button>
                            <Button variant="contained" onClick={handleSave}>Save</Button>
                        </Grid>
                    </Grid>
                </Grid>
            </Modal>
            {editedImage && (
                <div style={{ marginTop: '20px' }}>
                    <img
                        src={URL.createObjectURL(editedImage)}
                        alt="Edited"
                        style={{ width: '100%', maxWidth: '300px', height: 'auto' }}
                    />
                </div>
            )}
            {imageToEdit && !editedImage && (
                <div style={{ marginTop: '20px' }}>
                    <img
                        src={imageToEdit}
                        alt="To Edit"
                        style={{ width: '100%', maxWidth: '300px', height: 'auto' }}
                    />
                </div>
            )}
        </Paper>
    );
};

export default ImageCrop; 