import { useStore } from '@nanostores/react'
import { generatedImages, selectedImage, isGenerating } from '../stores'
import type { GeneratedImage } from '../stores'

export default function ImageGrid() {
  const images = useStore(generatedImages)
  const selected = useStore(selectedImage)
  const generating = useStore(isGenerating)

  const handleImageClick = (image: GeneratedImage) => {
    selectedImage.set(image)
  }

  if (generating) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <div className="text-center text-gray-300">
          <div className="text-lg mb-2">Generating images...</div>
          <div className="text-sm">Please wait while we fetch your images</div>
          <div className="mt-4">
            <div className="animate-pulse h-8 w-8 bg-white mx-auto" style={{ imageRendering: 'pixelated' }}></div>
          </div>
        </div>
      </div>
    )
  }

  if (images.length === 0) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <div className="text-center text-gray-500">
          <div className="text-lg mb-2">No images generated yet</div>
          <div className="text-sm">Click "Generate" to start</div>
        </div>
      </div>
    )
  }

  return (
    <div className="flex-1 p-6">
      <div className="grid grid-cols-5 gap-3">
        {images.map((image) => (
          <button
            key={image.id}
            onClick={() => handleImageClick(image)}
            className={`aspect-square border-2 transition-colors ${
              selected?.id === image.id
                ? 'border-white'
                : 'border-gray-700 hover:border-gray-500'
            }`}
          >
            <canvas
              ref={(canvas) => {
                if (canvas && image.canvas) {
                  const ctx = canvas.getContext('2d')!
                  canvas.width = image.canvas.width
                  canvas.height = image.canvas.height
                  canvas.style.width = '100%'
                  canvas.style.height = '100%'

                  if (image.generator === 'tixy' || image.generator === 'geometric-tiles') {
                    ctx.imageSmoothingEnabled = false
                  } else {
                    ctx.imageSmoothingEnabled = true
                  }

                  ctx.drawImage(image.canvas, 0, 0)
                }
              }}
              className="w-full h-full block"
              style={{ imageRendering: (image.generator === 'tixy' || image.generator === 'geometric-tiles') ? 'pixelated' : 'auto' }}
            />
          </button>
        ))}
      </div>
    </div>
  )
}