import { useState, useEffect } from 'react';
import { Header } from '@/components/layout/Header';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Filter, SlidersHorizontal, Zap, Clock, Star } from 'lucide-react';
import { AutocompleteSearch } from '@/components/search/AutocompleteSearch';
import { Ride } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { useNavigate } from 'react-router-dom';

export default function Rides() {
  const [rides, setRides] = useState<Ride[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filterCategory, setFilterCategory] = useState('all');
  const [filterStatus, setFilterStatus] = useState('all');
  const navigate = useNavigate();

  useEffect(() => {
    fetchRides();
  }, [sortBy, filterCategory, filterStatus]);

  const fetchRides = async () => {
    try {
      let query = supabase
        .from('rides')
        .select(`
          *, 
          park:parks!inner(name, slug, location:locations(*)),
          manufacturer:companies!rides_manufacturer_id_fkey(*)
        `);

      // Apply filters
      if (filterCategory !== 'all') {
        query = query.eq('category', filterCategory);
      }
      if (filterStatus !== 'all') {
        query = query.eq('status', filterStatus);
      }

      // Apply sorting
      switch (sortBy) {
        case 'rating':
          query = query.order('average_rating', { ascending: false });
          break;
        case 'speed':
          query = query.order('max_speed_kmh', { ascending: false, nullsFirst: false });
          break;
        case 'height':
          query = query.order('max_height_meters', { ascending: false, nullsFirst: false });
          break;
        case 'reviews':
          query = query.order('review_count', { ascending: false });
          break;
        default:
          query = query.order('name');
      }

      const { data } = await query;
      setRides(data || []);
    } catch (error) {
      console.error('Error fetching rides:', error);
    } finally {
      setLoading(false);
    }
  };

  const filteredRides = rides.filter(ride =>
    ride.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    ride.park?.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    ride.manufacturer?.name?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const getRideIcon = (category: string) => {
    switch (category) {
      case 'roller_coaster': return '🎢';
      case 'water_ride': return '🌊';
      case 'dark_ride': return '🎭';
      case 'flat_ride': return '🎡';
      case 'kiddie_ride': return '🎠';
      case 'transportation': return '🚂';
      default: return '🎢';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'operating': return 'bg-green-500/20 text-green-400 border-green-500/30';
      case 'seasonal': return 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30';
      case 'under_construction': return 'bg-blue-500/20 text-blue-400 border-blue-500/30';
      default: return 'bg-red-500/20 text-red-400 border-red-500/30';
    }
  };

  const formatCategory = (category: string) => {
    return category.split('_').map(word => 
      word.charAt(0).toUpperCase() + word.slice(1)
    ).join(' ');
  };

  const categories = [
    { value: 'all', label: 'All Categories' },
    { value: 'roller_coaster', label: 'Roller Coasters' },
    { value: 'flat_ride', label: 'Flat Rides' },
    { value: 'water_ride', label: 'Water Rides' },
    { value: 'dark_ride', label: 'Dark Rides' },
    { value: 'kiddie_ride', label: 'Kiddie Rides' },
    { value: 'transportation', label: 'Transportation' }
  ];

  const statusOptions = [
    { value: 'all', label: 'All Status' },
    { value: 'operating', label: 'Operating' },
    { value: 'seasonal', label: 'Seasonal' },
    { value: 'under_construction', label: 'Under Construction' },
    { value: 'closed', label: 'Closed' }
  ];

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="animate-pulse space-y-6">
            <div className="h-12 bg-muted rounded w-1/3"></div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {[...Array(8)].map((_, i) => (
                <div key={i} className="h-64 bg-muted rounded-lg"></div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <main className="container mx-auto px-4 py-8">
        {/* Page Header */}
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <div className="text-4xl">🎢</div>
            <h1 className="text-4xl font-bold">Rides & Attractions</h1>
          </div>
          <p className="text-lg text-muted-foreground">
            Explore amazing rides and attractions from theme parks worldwide
          </p>
          <div className="flex items-center gap-2 mt-2">
            <Badge variant="secondary">{filteredRides.length} rides found</Badge>
            <Badge variant="outline">{rides.filter(r => r.category === 'roller_coaster').length} roller coasters</Badge>
          </div>
        </div>

        {/* Search and Filters */}
        <div className="mb-8 space-y-4">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1">
              <AutocompleteSearch
                placeholder="Search rides by name, park, or manufacturer..."
                types={['ride']}
                limit={8}
                onSearch={(query) => setSearchQuery(query)}
                showRecentSearches={false}
              />
            </div>
            <div className="flex gap-2">
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="w-[180px]">
                  <SlidersHorizontal className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="name">Name A-Z</SelectItem>
                  <SelectItem value="rating">Highest Rated</SelectItem>
                  <SelectItem value="speed">Fastest</SelectItem>
                  <SelectItem value="height">Tallest</SelectItem>
                  <SelectItem value="reviews">Most Reviews</SelectItem>
                </SelectContent>
              </Select>
              
              <Select value={filterCategory} onValueChange={setFilterCategory}>
                <SelectTrigger className="w-[160px]">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {categories.map(category => (
                    <SelectItem key={category.value} value={category.value}>
                      {category.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-[140px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {statusOptions.map(status => (
                    <SelectItem key={status.value} value={status.value}>
                      {status.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>

        {/* Rides Grid */}
        {filteredRides.length > 0 ? (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6 gap-6">
            {filteredRides.map((ride) => (
              <Card 
                key={ride.id}
                className="group overflow-hidden border-border/50 bg-gradient-to-br from-card via-card to-card/80 hover:shadow-2xl hover:shadow-primary/20 transition-all duration-300 cursor-pointer hover:scale-[1.02]"
              >
                <div className="relative overflow-hidden">
                  {/* Image/Icon Section */}
                  <div className="aspect-video bg-gradient-to-br from-primary/20 via-secondary/20 to-accent/20 flex items-center justify-center relative">
                    {ride.image_url ? (
                      <img 
                        src={ride.image_url} 
                        alt={ride.name}
                        className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
                      />
                    ) : (
                      <div className="text-6xl opacity-50">
                        {getRideIcon(ride.category)}
                      </div>
                    )}
                    
                    {/* Gradient Overlay */}
                    <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
                    
                    {/* Status Badge */}
                    <Badge 
                      className={`absolute top-3 right-3 ${getStatusColor(ride.status)} border`}
                    >
                      {ride.status.replace('_', ' ').toUpperCase()}
                    </Badge>
                  </div>

                  <CardContent className="p-4 space-y-3">
                    {/* Header */}
                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <h3 className="font-bold text-lg group-hover:text-primary transition-colors line-clamp-1">
                          {ride.name}
                        </h3>
                        <span className="text-xl">{getRideIcon(ride.category)}</span>
                      </div>
                      
                      {ride.park?.name && (
                        <p className="text-sm text-muted-foreground">
                          at {ride.park.name}
                        </p>
                      )}
                    </div>

                    {/* Description */}
                    {ride.description && (
                      <p className="text-sm text-muted-foreground line-clamp-2">
                        {ride.description}
                      </p>
                    )}

                    {/* Category Badge */}
                    <Badge variant="outline" className="text-xs">
                      {formatCategory(ride.category)}
                    </Badge>

                    {/* Stats */}
                    <div className="flex items-center justify-between text-sm">
                      <div className="flex items-center gap-2">
                        {ride.max_speed_kmh && (
                          <div className="flex items-center gap-1">
                            <Zap className="w-3 h-3 text-primary" />
                            <span className="text-primary font-medium text-xs">{ride.max_speed_kmh}km/h</span>
                          </div>
                        )}
                        {ride.max_height_meters && (
                          <div className="flex items-center gap-1">
                            <span className="text-accent font-medium text-xs">{ride.max_height_meters}m</span>
                          </div>
                        )}
                        {ride.duration_seconds && (
                          <div className="flex items-center gap-1">
                            <Clock className="w-3 h-3 text-secondary" />
                            <span className="text-secondary font-medium text-xs">{Math.floor(ride.duration_seconds / 60)}min</span>
                          </div>
                        )}
                      </div>
                      
                      {ride.average_rating > 0 && (
                        <div className="flex items-center gap-1">
                          <Star className="w-3 h-3 fill-yellow-400 text-yellow-400" />
                          <span className="text-sm font-medium">{ride.average_rating.toFixed(1)}</span>
                        </div>
                      )}
                    </div>

                    {/* Action Button */}
                    <Button 
                      className="w-full mt-3 bg-gradient-to-r from-primary/80 to-secondary/80 hover:from-primary hover:to-secondary transition-all duration-300"
                      size="sm"
                    >
                      View Details
                    </Button>
                  </CardContent>
                </div>
              </Card>
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <div className="text-6xl mb-4">🎢</div>
            <h3 className="text-xl font-semibold mb-2">No rides found</h3>
            <p className="text-muted-foreground">
              Try adjusting your search criteria or filters
            </p>
          </div>
        )}
      </main>
    </div>
  );
}