export type PixelCrop = {
  x: number;
  y: number;
  width: number;
  height: number;
};

export type CropImageOptions = {
  rotation?: number;
  flipH?: boolean;
  flipV?: boolean;
  brightness?: number;
  contrast?: number;
  saturate?: number;
  mimeType?: string;
  quality?: number;
};

function createImage(url: string): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.addEventListener('load', () => resolve(image));
    image.addEventListener('error', () =>
      reject(new Error('Failed to load image')),
    );
    // blob:/data: sources are same-origin and never taint the canvas, so we
    // only request CORS access for remote http(s) URLs.
    if (!url.startsWith('blob:') && !url.startsWith('data:')) {
      image.crossOrigin = 'anonymous';
    }
    image.src = url;
  });
}

function getRadianAngle(degrees: number): number {
  return (degrees * Math.PI) / 180;
}

/**
 * Bounding box of an image rotated by the given angle.
 */
function rotateSize(width: number, height: number, rotation: number) {
  const rotRad = getRadianAngle(rotation);
  return {
    width:
      Math.abs(Math.cos(rotRad) * width) + Math.abs(Math.sin(rotRad) * height),
    height:
      Math.abs(Math.sin(rotRad) * width) + Math.abs(Math.cos(rotRad) * height),
  };
}

/**
 * Renders the source image with rotation, flips and color adjustments, then
 * extracts the requested crop region and returns it as a base64 data URL,
 * ready to be sent to the server (which decodes the base64 back into a file).
 *
 * The source is expected to be a same-origin data: URL (coming from the
 * server's base64 method), so the canvas is never tainted.
 */
export async function getCroppedImg(
  imageSrc: string,
  pixelCrop: PixelCrop,
  options: CropImageOptions = {},
): Promise<string> {
  const {
    rotation = 0,
    flipH = false,
    flipV = false,
    brightness = 100,
    contrast = 100,
    saturate = 100,
    mimeType = 'image/png',
    quality = 0.92,
  } = options;

  const image = await createImage(imageSrc);

  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  if (!ctx) {
    throw new Error('Failed to get 2D canvas context');
  }

  const rotRad = getRadianAngle(rotation);
  const { width: bBoxWidth, height: bBoxHeight } = rotateSize(
    image.width,
    image.height,
    rotation,
  );

  canvas.width = bBoxWidth;
  canvas.height = bBoxHeight;

  ctx.filter = `brightness(${brightness}%) contrast(${contrast}%) saturate(${saturate}%)`;
  ctx.translate(bBoxWidth / 2, bBoxHeight / 2);
  ctx.rotate(rotRad);
  ctx.scale(flipH ? -1 : 1, flipV ? -1 : 1);
  ctx.translate(-image.width / 2, -image.height / 2);
  ctx.drawImage(image, 0, 0);

  const croppedCanvas = document.createElement('canvas');
  const croppedCtx = croppedCanvas.getContext('2d');
  if (!croppedCtx) {
    throw new Error('Failed to get 2D canvas context');
  }

  croppedCanvas.width = Math.max(1, Math.round(pixelCrop.width));
  croppedCanvas.height = Math.max(1, Math.round(pixelCrop.height));

  croppedCtx.drawImage(
    canvas,
    pixelCrop.x,
    pixelCrop.y,
    pixelCrop.width,
    pixelCrop.height,
    0,
    0,
    pixelCrop.width,
    pixelCrop.height,
  );

  return croppedCanvas.toDataURL(mimeType, quality);
}
