import { useState } from 'react';
import { shire } from '@/api/shireClient';
import { X, ImagePlus } from 'lucide-react';

export default function ImageUploader({ images, onChange }) {
  const [uploading, setUploading] = useState(false);

  const handleFiles = async (e) => {
    const files = Array.from(e.target.files);
    if (!files.length) return;
    const remaining = 10 - images.length;
    const toUpload = files.slice(0, remaining);
    setUploading(true);
    const urls = await Promise.all(
      toUpload.map(async (file) => {
        const { file_url } = await shire.integrations.Core.UploadFile({ file });
        return file_url;
      })
    );
    onChange([...images, ...urls]);
    setUploading(false);
  };

  const remove = (idx) => {
    const next = images.filter((_, i) => i !== idx);
    onChange(next);
  };

  return (
    <div className="space-y-3">
      <label className="block text-xs font-semibold text-gray-700">
        Product Photos <span className="text-gray-400 font-normal">(up to 10)</span>
      </label>
      <div className="grid grid-cols-3 sm:grid-cols-5 gap-2">
        {images.map((url, i) => (
          <div key={i} className="relative aspect-square rounded-lg overflow-hidden border border-gray-200 bg-gray-50">
            <img src={url} alt="" className="w-full h-full object-cover" />
            <button
              onClick={() => remove(i)}
              className="absolute top-1 right-1 bg-black/60 rounded-full p-0.5 text-white hover:bg-black/80"
            >
              <X size={10} />
            </button>
            {i === 0 && (
              <span className="absolute bottom-1 left-1 text-xs bg-orange-500 text-white px-1 rounded font-medium">Main</span>
            )}
          </div>
        ))}
        {images.length < 10 && (
          <label className={`aspect-square rounded-lg border-2 border-dashed flex flex-col items-center justify-center cursor-pointer transition-colors
            ${uploading ? 'border-gray-200 bg-gray-50' : 'border-gray-300 hover:border-orange-400 hover:bg-orange-50'}`}>
            {uploading ? (
              <div className="w-5 h-5 border-2 border-orange-200 border-t-orange-500 rounded-full animate-spin" />
            ) : (
              <>
                <ImagePlus size={18} className="text-gray-400" />
                <span className="text-xs text-gray-400 mt-1">Add</span>
              </>
            )}
            <input
              type="file"
              accept="image/*"
              multiple
              onChange={handleFiles}
              className="hidden"
              disabled={uploading}
            />
          </label>
        )}
      </div>
    </div>
  );
}
