import type { GeneratedImage } from '../stores'

export async function generatePicsumImages(count: number, size: number): Promise<GeneratedImage[]> {
  const images: GeneratedImage[] = []
  const promises: Promise<GeneratedImage | null>[] = []

  for (let i = 0; i < count; i++) {
    const promise = loadPicsumImage(size, i)
    promises.push(promise)
  }

  const results = await Promise.allSettled(promises)

  for (const result of results) {
    if (result.status === 'fulfilled' && result.value) {
      images.push(result.value)
    }
  }

  return images
}

const highQualityIds = [
  1, 2, 3, 5, 6, 8, 9, 10, 11, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
  35, 36, 37, 39, 40, 42, 43, 44, 47, 48, 49, 50, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
  64, 65, 67, 68, 69, 70, 72, 73, 74, 75, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  91, 92, 96, 97, 98, 99, 100, 101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 116
]

async function loadPicsumImage(size: number, index: number): Promise<GeneratedImage | null> {
  try {
    const imageId = highQualityIds[Math.floor(Math.random() * highQualityIds.length)]
    const url = `https://picsum.photos/id/${imageId}/${size}/${size}?grayscale`

    const img = new Image()
    img.crossOrigin = 'anonymous'

    return new Promise((resolve, reject) => {
      img.onload = () => {
        try {
          const canvas = document.createElement('canvas')
          canvas.width = size
          canvas.height = size

          const ctx = canvas.getContext('2d')!
          ctx.drawImage(img, 0, 0, size, size)

          const imageData = ctx.getImageData(0, 0, size, size)

          resolve({
            id: `picsum-${Date.now()}-${index}`,
            canvas,
            imageData,
            generator: 'picsum',
            params: { url, imageId }
          })
        } catch (error) {
          console.error('Error processing Picsum image:', error)
          resolve(null)
        }
      }

      img.onerror = () => {
        console.error('Failed to load Picsum image:', url)
        resolve(null)
      }

      img.src = url
    })
  } catch (error) {
    console.error('Error creating Picsum image:', error)
    return null
  }
}