
import React, { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { AspectRatio } from "@/components/ui/aspect-ratio";
import { Search, Check } from "lucide-react";
import { toast } from "sonner";

interface ImageGalleryProps {
  onSelect: (url: string) => void;
  aspectRatio: number;
  folder?: string;
}

interface StorageFile {
  name: string;
  url: string;
  created_at: string;
}

const ImageGallery = ({ onSelect, aspectRatio, folder }: ImageGalleryProps) => {
  const [images, setImages] = useState<StorageFile[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedImage, setSelectedImage] = useState<string | null>(null);

  useEffect(() => {
    loadImages();
  }, [folder]);

  const loadImages = async () => {
    try {
      const { data, error } = await supabase.storage
        .from('images')
        .list(folder || '', {
          limit: 50,
          sortBy: { column: 'created_at', order: 'desc' }
        });

      if (error) throw error;

      const imageUrls = data
        ?.filter(file => file.name !== '.emptyFolderPlaceholder')
        .map(file => {
          const { data: { publicUrl } } = supabase.storage
            .from('images')
            .getPublicUrl(`${folder}/${file.name}`);
          
          return {
            name: file.name,
            url: publicUrl,
            created_at: file.created_at || ''
          };
        }) || [];

      setImages(imageUrls);
    } catch (error) {
      console.error('Erreur lors du chargement des images:', error);
      toast.error('Erreur lors du chargement de la galerie');
    } finally {
      setLoading(false);
    }
  };

  const filteredImages = images.filter(image =>
    image.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleSelect = (url: string) => {
    setSelectedImage(url);
    onSelect(url);
    toast.success('Image sélectionnée');
  };

  if (loading) {
    return (
      <div className="text-center py-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
        <p className="text-gray-600">Chargement de la galerie...</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="relative">
        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
        <Input
          placeholder="Rechercher dans la galerie..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="pl-10"
        />
      </div>

      {filteredImages.length === 0 ? (
        <div className="text-center py-8 text-gray-500">
          {searchTerm ? 'Aucune image trouvée' : 'Aucune image dans la galerie'}
        </div>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-4 max-h-80 overflow-y-auto">
          {filteredImages.map((image) => (
            <Card
              key={image.url}
              className={`cursor-pointer transition-all hover:shadow-md ${
                selectedImage === image.url ? 'ring-2 ring-blue-500' : ''
              }`}
              onClick={() => handleSelect(image.url)}
            >
              <CardContent className="p-2">
                <div className="relative">
                  <AspectRatio ratio={aspectRatio}>
                    <img
                      src={image.url}
                      alt={image.name}
                      className="w-full h-full object-cover rounded"
                    />
                  </AspectRatio>
                  {selectedImage === image.url && (
                    <div className="absolute top-1 right-1 bg-blue-500 text-white rounded-full p-1">
                      <Check className="h-3 w-3" />
                    </div>
                  )}
                </div>
                <p className="text-xs text-gray-500 mt-1 truncate">
                  {image.name}
                </p>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
};

export default ImageGallery;
