import React, { useState, useRef } from 'react';
import ReactCrop, { centerCrop, makeAspectCrop } from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Loader2, UploadCloud } from "lucide-react";
import { useTranslation } from '@/hooks/useTranslation';

function centerAspectCrop(mediaWidth, mediaHeight, aspect) {
    return centerCrop(
        makeAspectCrop({ unit: '%', width: 90 }, aspect, mediaWidth, mediaHeight),
        mediaWidth, mediaHeight
    );
}

export default function ImageCropper({ open, onOpenChange, onSave, aspectRatio = 1 }) {
    const { t } = useTranslation();
    const [imgSrc, setImgSrc] = useState('');
    const [crop, setCrop] = useState();
    const [completedCrop, setCompletedCrop] = useState();
    const [loading, setLoading] = useState(false);
    const imgRef = useRef(null);

    function onFileSelect(e) {
        if (e.target.files && e.target.files.length > 0) {
            setCrop(undefined);
            const reader = new FileReader();
            reader.addEventListener('load', () => setImgSrc(reader.result?.toString() || ''));
            reader.readAsDataURL(e.target.files[0]);
        }
    }

    function onImageLoad(e) {
        const { width, height } = e.currentTarget;
        setCrop(centerAspectCrop(width, height, aspectRatio));
    }

    async function handleSave() {
        if (!completedCrop || !imgRef.current) return;
        setLoading(true);

        const image = imgRef.current;
        const canvas = document.createElement('canvas');
        const scaleX = image.naturalWidth / image.width;
        const scaleY = image.naturalHeight / image.height;
        const pixelRatio = window.devicePixelRatio;
        
        canvas.width = Math.floor(completedCrop.width * scaleX * pixelRatio);
        canvas.height = Math.floor(completedCrop.height * scaleY * pixelRatio);
        
        const ctx = canvas.getContext('2d');
        ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
        ctx.imageSmoothingQuality = 'high';

        ctx.drawImage(
            image,
            completedCrop.x * scaleX, completedCrop.y * scaleY,
            completedCrop.width * scaleX, completedCrop.height * scaleY,
            0, 0,
            completedCrop.width * scaleX, completedCrop.height * scaleY
        );

        canvas.toBlob(
            (blob) => {
                if (blob) onSave(blob);
                setLoading(false);
                onOpenChange(false);
                setImgSrc('');
            },
            'image/jpeg',
            0.95
        );
    }

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[625px]">
                <DialogHeader>
                    <DialogTitle>{t('Update Photo')}</DialogTitle>
                </DialogHeader>
                <div className="py-4 space-y-4">
                    {!imgSrc && (
                        <div className="flex flex-col items-center justify-center p-8 border-2 border-dashed rounded-lg">
                            <UploadCloud className="w-12 h-12 text-muted-foreground" />
                            <p className="mt-2 text-sm text-muted-foreground">{t('Select an image file to crop')}</p>
                            <Input id="picture" type="file" accept="image/*" onChange={onFileSelect} className="mt-4" />
                        </div>
                    )}
                    {imgSrc && (
                        <ReactCrop
                            crop={crop}
                            onChange={(_, percentCrop) => setCrop(percentCrop)}
                            onComplete={(c) => setCompletedCrop(c)}
                            aspect={aspectRatio}
                            minWidth={100}
                            className="max-h-[60vh]"
                        >
                            <img ref={imgRef} alt={t('Crop area')} src={imgSrc} onLoad={onImageLoad} />
                        </ReactCrop>
                    )}
                </div>
                <DialogFooter>
                    <Button variant="outline" onClick={() => { onOpenChange(false); setImgSrc(''); }}>{t('Cancel')}</Button>
                    <Button onClick={handleSave} disabled={!completedCrop || loading}>
                        {loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
                        {t('Save Photo')}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}