import type { Area } from 'react-easy-crop'

function createImage(url: string): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    const image = new Image()
    image.addEventListener('load', () => resolve(image))
    image.addEventListener('error', reject)
    image.src = url
  })
}

export async function getCroppedImage(
  imageSrc: string,
  pixelCrop: Area,
  format: 'jpeg' | 'png' = 'jpeg',
): Promise<string> {
  const image = await createImage(imageSrc)
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  if (!ctx) throw new Error('Could not get canvas context')

  canvas.width = pixelCrop.width
  canvas.height = pixelCrop.height

  if (format === 'png') {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
  }

  ctx.drawImage(
    image,
    pixelCrop.x,
    pixelCrop.y,
    pixelCrop.width,
    pixelCrop.height,
    0,
    0,
    pixelCrop.width,
    pixelCrop.height,
  )

  if (format === 'png') {
    return canvas.toDataURL('image/png')
  }

  return canvas.toDataURL('image/jpeg', 0.92)
}
