import { Button } from "@mui/material";
import { useState } from "react";
import Cropper from "react-easy-crop";
import { cropImage, dataURLtoFile } from "./cropImg";

function Crop({ data, uploadImg, handleClose }) {
  const [crop, setCrop] = useState({ x: 0, y: 0 });
  const [zoom, setZoom] = useState(1);
  const [croppedAreaPixels, setCroppedAreaPixels] = useState(null);

  const onComplete = async (imagePromise, name) => {
    const dataUrl = await imagePromise;

    const file = dataURLtoFile(dataUrl, name);

    uploadImg({ blob: dataUrl, file });
  };

  return (
    <div className="mt-[16px]">
      <div className="px-[24px]">
        <div className="relative w-[424px] h-[380px] rounded-[8px] overflow-hidden">
          <Cropper
            crop={crop}
            zoom={zoom}
            aspect={1}
            image={data.blob}
            onCropChange={setCrop}
            onCropComplete={(_, croppedAreaPixels) =>
              setCroppedAreaPixels(croppedAreaPixels)
            }
            onZoomChange={setZoom}
          />
        </div>
      </div>
      <div className="flex items-center justify-end gap-[16px] mt-[16px]">
        <Button
          variant="outlined"
          onClick={handleClose}
          className="!text-[16px] !max-w-[calc(50%_-_8px)] dark:!bg-[#C7CEF4] dark:!text-[#5559CE] !font-medium !border-[#5559CE] !py-[5px] md:!py-[7px] lg:!py-[9px] !shadow-none"
        >
          انصراف
        </Button>
        <Button
          variant="contained"
          onClick={() =>
            onComplete(cropImage(data.blob, croppedAreaPixels), data.file?.name)
          }
          className="!text-[16px] !max-w-[calc(50%_-_8px)] !font-medium !shadow-none !py-[5px] md:!py-[7px] lg:!py-[9px]"
        >
          ذخیره
        </Button>
      </div>
    </div>
  );
}

export default Crop;
