import { useEffect, useState } from 'react';
import { supabase } from '@/lib/supabaseClient';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Camera } from 'lucide-react';

interface RecentPhotosPreviewProps {
  rideId: string;
  onViewAll: () => void;
}

interface Photo {
  id: string;
  image_url: string;
  caption: string | null;
}

export function RecentPhotosPreview({ rideId, onViewAll }: RecentPhotosPreviewProps) {
  const [photos, setPhotos] = useState<Photo[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchPhotos() {
      const { data, error } = await supabase
        .from('reviews')
        .select(`
          id,
          user_id,
          created_at,
          review_photos!inner(
            cloudflare_image_url,
            caption,
            order_index,
            id
          )
        `)
        .eq('ride_id', rideId)
        .eq('moderation_status', 'approved')
        .order('created_at', { ascending: false })
        .limit(10);

      if (!error && data) {
        const allPhotos: Photo[] = [];
        data.forEach((review: any) => {
          if (review.review_photos && Array.isArray(review.review_photos)) {
            review.review_photos.forEach((photo: any) => {
              if (allPhotos.length < 4) {
                allPhotos.push({
                  id: photo.id || Math.random().toString(),
                  image_url: photo.cloudflare_image_url,
                  caption: photo.caption || null
                });
              }
            });
          }
        });
        setPhotos(allPhotos);
      }
      setLoading(false);
    }

    fetchPhotos();
  }, [rideId]);

  if (loading || photos.length === 0) {
    return null;
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Camera className="w-5 h-5" />
          Recent Photos
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {photos.map((photo) => (
            <div
              key={photo.id}
              className="aspect-square rounded-lg overflow-hidden bg-accent cursor-pointer hover:opacity-80 transition-opacity"
              onClick={onViewAll}
            >
              <img
                src={photo.image_url}
                alt={photo.caption || 'Ride photo'}
                className="w-full h-full object-cover"
              />
            </div>
          ))}
        </div>
        <div className="mt-4 text-center">
          <Button variant="outline" onClick={onViewAll} className="w-full">
            View All Photos
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
