import {
  Button,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Slider,
} from "@mui/material";
import React from "react";
import Cropper, { Area } from "react-easy-crop";

export function ImageCropperDialog(p: {
  src: string;
  onCancel: () => void;
  onSubmit: (croppedArea: Area | undefined) => void;
  processing: boolean;
  aspect?: number;
}): React.ReactElement {
  const [crop, setCrop] = React.useState({ x: 0, y: 0 });
  const [zoom, setZoom] = React.useState(1);
  const [croppedArea, setCroppedArea] = React.useState<Area>();

  const submit = () => {
    p.onSubmit(croppedArea);
  };

  return (
    <Dialog open={true} onClose={p.onCancel}>
      <DialogTitle>Rogner l'image</DialogTitle>
      <DialogContent>
        <div style={{ width: "400px", height: "350px" }}>
          <div style={{ height: "320px" }}>
            <Cropper
              image={p.src}
              crop={crop}
              zoom={zoom}
              aspect={p.aspect}
              onCropChange={setCrop}
              onCropComplete={(_a, b) => setCroppedArea(b)}
              onZoomChange={setZoom}
              maxZoom={4}
            />
          </div>

          <Slider
            value={zoom}
            step={0.1}
            min={1}
            max={4}
            onChange={(_e, v) => setZoom(Number(v))}
          />
        </div>
      </DialogContent>
      <DialogActions>
        {p.processing ? (
          <CircularProgress size={"1rem"} />
        ) : (
          <>
            <Button onClick={p.onCancel}>Annuler</Button>
            <Button onClick={submit} autoFocus>
              Envoyer
            </Button>
          </>
        )}
      </DialogActions>
    </Dialog>
  );
}
