import { Cropper, CropperRef } from 'react-advanced-cropper';
import {
 Box,
 Button,
 Dialog,
 DialogContent,
 DialogTitle,
 useTheme,
} from '@mui/material';
import { useRef } from 'react';
import 'react-advanced-cropper/dist/style.css';

export interface ImageCropDialogProps {
 onCancel: () => void;
 onCropComplete: (file: File) => void;
 cropImageUrl: string;
}

export function ImageCropDialog(props: ImageCropDialogProps) {
 const cropperRef = useRef<CropperRef>(null);
 const { cropImageUrl, onCancel, onCropComplete } = props;
 const handleCrop = async () => {
  const cropper = cropperRef.current;
  if (!cropper) return;
  const canvas = cropper.getCanvas();
  if (!canvas) return;
  canvas.toBlob((blob) => {
   if (!blob) return;

   const file = new File([blob], `crop-${Date.now()}.jpeg`, {
    type: 'image/jpeg',
    lastModified: Date.now(),
   });

   onCropComplete(file);
  }, 'image/jpeg');
 };
 const theme = useTheme();
 return (
  <Dialog
   maxWidth='xl'
   open={!!cropImageUrl}
   sx={{ bgcolor: theme.palette.background.paper }}
   fullWidth
  >
   <DialogTitle sx={{ display: 'none' }} />
   <DialogContent
    sx={{
     p: 0,
     height: '90dvh',
     bgcolor: theme.palette.background.paper,
     backdropFilter: 'blur(8px)',

     overflow: 'hidden',
    }}
   >
    <Box
     flex={1}
     sx={{ width: '100%', height: '100%',bgcolor: theme.palette.background.paper, }}
     display='flex'
     flexDirection={'column'}
    >
     <Box
      sx={{
       height: 'calc(100% - 40px)',
       width: '100%',
       padding: '20px',
      bgcolor: theme.palette.background.paper,
       borderRadius: '20px',
      }}
     >
      <Cropper
       ref={cropperRef}
       src={cropImageUrl}
       style={{
        height: '100%',
        borderRadius: '20px',
        width: '100%',
        background: 'rgba(15,23,42,0.95)',
       }}
      />
     </Box>
     <Box
      flex={1}
      display='flex'
      gap={2}
      sx={{ height: '40px', padding: '8px 24px' }}
      justifyContent={'space-between'}
     >
      <Button variant='outlined' onClick={onCancel}>
       Cancel
      </Button>
      <Button variant='contained' onClick={handleCrop}>
       Crop
      </Button>
     </Box>
    </Box>
   </DialogContent>
  </Dialog>
 );
}
