import { useCallback, useState } from 'react';
import Debug from 'debug';
import Cropper from 'react-easy-crop';

import type { ImageCrop } from './types';

const debug = Debug('songwhip/CropImage');

const NOOP = () => {};

const CropImage = ({
  onChange = NOOP,
  onZoomChange = NOOP,
  src,
  zoom = 1,
}: {
  onChange: (params: { crop: ImageCrop }) => void;
  onZoomChange: (params: { zoom: number }) => void;
  src: string;
  zoom?: number;
}) => {
  const [crop, setCrop] = useState({ x: 0, y: 0 });

  const onCropComplete = useCallback(
    (croppedArea, croppedAreaPixels: ImageCrop) => {
      debug('crop complete', {
        croppedArea,
        croppedAreaPixels,
        zoom,
      });

      onChange({
        crop: croppedAreaPixels,
      });
    },
    [zoom]
  );

  return (
    <div
      data-testid="cropImage"
      style={{
        height: 240,
        position: 'relative',
        background: '#444',
      }}
    >
      <Cropper
        image={src}
        crop={crop}
        zoom={zoom}
        minZoom={0.1}
        // square
        aspect={1 / 1}
        // Don't lock image to boundaries of the crop-frame. This effectively
        // allows users to add extra whitespace to the final cropped image.
        restrictPosition={false}
        onCropChange={(crop) => {
          // debug('on crop change', crop);
          setCrop(crop);
        }}
        onCropComplete={onCropComplete}
        onZoomChange={(zoom) => {
          // debug('on zoom change', zoom);
          onZoomChange({ zoom });
        }}
      />
    </div>
  );
};

export default CropImage;
