import { useState, useEffect } from 'react';
import apiClient from '../api/client';

export default function ImagePicker({ slug, currentImage, onSelect }) {
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadImages() {
      try {
        const res = await apiClient.get('/api/templates/images');
        setImages(res.data.images || []);
      } catch (err) {
        console.error('Failed to load images', err);
      } finally {
        setLoading(false);
      }
    }
    loadImages();
  }, []);

  if (loading) {
    return <div className="text-sm text-gray-400">Loading brand images…</div>;
  }

  if (images.length === 0) {
    return <div className="text-sm text-gray-500 italic bg-gray-50 border border-gray-100 px-4 py-3 rounded-lg">No images available for this brand.</div>;
  }

  return (
    <div className="grid grid-cols-3 gap-3">
      {images.map((img, i) => {
        const isSelected = currentImage === img.url;
        return (
          <button
            key={i}
            onClick={() => onSelect(img.url)}
            className={`relative rounded-lg overflow-hidden border-2 aspect-video transition-all ${
              isSelected
                ? 'border-indigo-600 ring-2 ring-indigo-600 ring-opacity-50 shadow-md'
                : 'border-transparent hover:border-gray-300 opacity-80 hover:opacity-100 shadow-sm'
            }`}
          >
            <img src={img.url} alt={`brand-pic-${i}`} className="w-full h-full object-cover" />
            <div className={`absolute inset-0 bg-indigo-600/20 transition-opacity ${isSelected ? 'opacity-100' : 'opacity-0'}`} />
            {isSelected && (
              <div className="absolute top-1.5 right-1.5 w-5 h-5 bg-indigo-600 rounded-full flex items-center justify-center shadow-lg border-2 border-white">
                <svg className="w-3 h-3 text-white" viewBox="0 0 20 20" fill="currentColor"><path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" /></svg>
              </div>
            )}
          </button>
        );
      })}
    </div>
  );
}
