import imageCompression from 'browser-image-compression'
import Swal from 'sweetalert2'

export const MAX_IMAGE_SIZE_BYTES = 1.5 * 1024 * 1024 // 1.5 MB

export async function compressImageIfNeeded(file: File): Promise<File> {
  if (file.size <= MAX_IMAGE_SIZE_BYTES) return file

  const options = {
    maxSizeMB: 1.5,
    maxWidthOrHeight: 1920,
    useWebWorker: true
  }

  const compressedBlob = await imageCompression(file, options)

  const compressedFile = new File([compressedBlob], file.name, {
    type: compressedBlob.type || file.type,
    lastModified: Date.now()
  })

  return compressedFile
}

export async function promptAndProcessImage(file: File): Promise<File | null> {
  if (file.size <= MAX_IMAGE_SIZE_BYTES) {
    return file
  }

  const sizeInMb = file.size / (1024 * 1024)

  const result = await Swal.fire({
    title: 'حجم الصورة كبير',
    text: `حجم الصورة ${sizeInMb.toFixed(2)} ميغابايت، سيتم ضغطها قبل الرفع في حال الموافقة.`,
    icon: 'warning',
    showCancelButton: true,
    showDenyButton: false,
    confirmButtonText: 'ضغط ورفع',
    cancelButtonText: 'إلغاء',
    reverseButtons: true
  })

  if (result.isConfirmed) {
    const compressed = await compressImageIfNeeded(file)
    return compressed
  }

  return null
}
