import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { supabase } from '@/integrations/supabase/client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { RideCard } from '@/components/rides/RideCard';

interface SimilarRidesProps {
  currentRideId: string;
  parkId: string;
  parkSlug: string;
  category: string;
}

interface SimilarRide {
  id: string;
  name: string;
  slug: string;
  image_url: string | null;
  average_rating: number | null;
  status: string;
  category: string;
  description: string | null;
  max_speed_kmh: number | null;
  max_height_meters: number | null;
  duration_seconds: number | null;
  review_count: number | null;
  park: {
    name: string;
    slug: string;
  };
}

export function SimilarRides({ currentRideId, parkId, parkSlug, category }: SimilarRidesProps) {
  const [rides, setRides] = useState<SimilarRide[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchSimilarRides() {
      const { data, error } = await supabase
        .from('rides')
        .select(`
          id, 
          name, 
          slug, 
          image_url, 
          average_rating, 
          status,
          category,
          description,
          max_speed_kmh,
          max_height_meters,
          duration_seconds,
          review_count,
          park:parks!inner(name, slug)
        `)
        .eq('park_id', parkId)
        .eq('category', category)
        .neq('id', currentRideId)
        .order('average_rating', { ascending: false })
        .limit(4);

      if (!error && data) {
        setRides(data);
      }
      setLoading(false);
    }

    fetchSimilarRides();
  }, [currentRideId, parkId, category]);

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

  return (
    <Card>
      <CardHeader>
        <CardTitle>Similar Rides You Might Enjoy</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 lg:gap-5 xl:gap-4">
          {rides.map((ride) => (
            <RideCard 
              key={ride.id} 
              ride={ride} 
              showParkName={false}
              parkSlug={parkSlug}
            />
          ))}
        </div>
        <div className="mt-4 text-center">
          <Button variant="outline" asChild>
            <Link to={`/parks/${parkSlug}/rides`}>View All Rides</Link>
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
