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

const searchTerms = [
  'painting', 'sculpture', 'drawing', 'pottery', 'portrait', 'landscape',
  'impressionist', 'modern', 'contemporary', 'abstract', 'still life',
  'figure', 'nature', 'urban', 'color', 'light', 'texture', 'pattern',
  'architecture', 'street', 'woman', 'man', 'cat', 'dog', 'flower', 'tree'
]

interface ArticArtwork {
  id: number
  title: string
  artist_display: string
  date_display: string
  image_id: string
  is_public_domain: boolean
  medium_display: string
  department_title: string
}

interface ArticSearchResponse {
  data: ArticArtwork[]
  pagination: {
    total: number
    limit: number
    offset: number
  }
}

export async function generateArtInstituteImages(count: number, size: number): Promise<GeneratedImage[]> {
  const images: GeneratedImage[] = []
  const maxRetries = count * 3 // Try 3x more objects to account for failures

  for (let attempt = 0; attempt < maxRetries && images.length < count; attempt++) {
    try {
      const image = await loadArtInstituteImage(size, attempt)
      if (image) {
        images.push(image)
      }
    } catch (error) {
      console.error(`Met Museum attempt ${attempt + 1} failed:`, error)
    }
  }

  return images
}

async function loadArtInstituteImage(size: number, index: number): Promise<GeneratedImage | null> {
  try {
    const searchTerm = searchTerms[Math.floor(Math.random() * searchTerms.length)]

    const searchUrl = `https://api.artic.edu/api/v1/artworks/search?q=${encodeURIComponent(searchTerm)}&query[term][is_public_domain]=true&limit=50&fields=id,title,artist_display,date_display,image_id,is_public_domain,medium_display,department_title`
    const searchResponse = await fetch(searchUrl)

    if (!searchResponse.ok) {
      throw new Error('Failed to search Art Institute')
    }

    const searchData: ArticSearchResponse = await searchResponse.json()

    if (!searchData.data || searchData.data.length === 0) {
      throw new Error('No artworks found')
    }

    // Filter artworks that have images
    const artworksWithImages = searchData.data.filter(artwork => artwork.image_id && artwork.is_public_domain)

    if (artworksWithImages.length === 0) {
      throw new Error('No artworks with images found')
    }

    const artwork = artworksWithImages[Math.floor(Math.random() * artworksWithImages.length)]

    // Construct IIIF image URL - 512px width, auto height
    const imageUrl = `https://www.artic.edu/iiif/2/${artwork.image_id}/full/512,/0/default.jpg`

    return new Promise((resolve) => {
      const img = new Image()
      img.crossOrigin = 'anonymous'

      img.onload = () => {
        try {
          const canvas = document.createElement('canvas')
          canvas.width = size
          canvas.height = size

          const ctx = canvas.getContext('2d')!

          // Calculate aspect ratio and center the image
          const imgAspect = img.width / img.height
          let drawWidth = size
          let drawHeight = size
          let drawX = 0
          let drawY = 0

          if (imgAspect > 1) {
            drawHeight = size / imgAspect
            drawY = (size - drawHeight) / 2
          } else {
            drawWidth = size * imgAspect
            drawX = (size - drawWidth) / 2
          }

          // Black background
          ctx.fillStyle = '#000000'
          ctx.fillRect(0, 0, size, size)

          // Draw the image
          ctx.drawImage(img, drawX, drawY, drawWidth, drawHeight)

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

          resolve({
            id: `artic-${Date.now()}-${index}`,
            canvas,
            imageData,
            generator: 'art-institute',
            params: {
              artworkId: artwork.id,
              title: artwork.title || 'Untitled',
              artist: artwork.artist_display || 'Unknown Artist',
              date: artwork.date_display || 'Unknown Date',
              medium: artwork.medium_display || 'Unknown Medium',
              department: artwork.department_title || 'Unknown Department',
              searchTerm
            }
          })
        } catch (error) {
          console.error('Error processing Art Institute image:', error)
          resolve(null)
        }
      }

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

      // Set timeout for slow loading images
      setTimeout(() => {
        if (!img.complete) {
          console.error('Art Institute image load timeout:', imageUrl)
          resolve(null)
        }
      }, 8000)

      img.src = imageUrl
    })
  } catch (error) {
    console.error('Error creating Met Museum image:', error)
    return null
  }
}