import { useState, useEffect } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ParkCard } from '@/components/parks/ParkCard';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Star, TrendingUp, Plus, MapPin, Clock, Zap } from 'lucide-react';
import { Park, Ride } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';

export function ContentTabs() {
  const [popularParks, setPopularParks] = useState<Park[]>([]);
  const [trendingParks, setTrendingParks] = useState<Park[]>([]);
  const [popularRides, setPopularRides] = useState<Ride[]>([]);
  const [trendingRides, setTrendingRides] = useState<Ride[]>([]);
  const [recentParks, setRecentParks] = useState<Park[]>([]);
  const [recentRides, setRecentRides] = useState<Ride[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchContent();
  }, []);

  const fetchContent = async () => {
    try {
      // Most Popular Parks (by rating)
      const { data: popular } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .order('average_rating', { ascending: false })
        .limit(12);

      // Trending Parks (by review count)
      const { data: trending } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .order('review_count', { ascending: false })
        .limit(12);

      // Recently Added Parks
      const { data: recent } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .order('created_at', { ascending: false })
        .limit(12);

      // Popular Rides (by rating)
      const { data: popularRidesData } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .order('average_rating', { ascending: false })
        .limit(12);

      // Trending Rides (by review count) 
      const { data: trendingRidesData } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .order('review_count', { ascending: false })
        .limit(12);

      // Recently Added Rides
      const { data: recentRidesData } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .order('created_at', { ascending: false })
        .limit(12);

      setPopularParks(popular || []);
      setTrendingParks(trending || []);
      setRecentParks(recent || []);
      setPopularRides(popularRidesData || []);
      setTrendingRides(trendingRidesData || []);
      setRecentRides(recentRidesData || []);
    } catch (error) {
      console.error('Error fetching content:', error);
    } finally {
      setLoading(false);
    }
  };

  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 RideCard = ({ ride }: { ride: Ride }) => (
    <Card 
      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 && (
              <div className="flex items-center text-sm text-muted-foreground">
                <MapPin className="w-3 h-3 mr-1" />
                {ride.park.name}
                {ride.park.location?.city && `, ${ride.park.location.city}`}
              </div>
            )}
          </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-4">
              {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">{ride.max_speed_kmh}</span>
                  <span className="text-muted-foreground text-xs">km/h</span>
                </div>
              )}
              {ride.max_height_meters && (
                <div className="flex items-center gap-1">
                  <span className="text-accent font-medium">{ride.max_height_meters}</span>
                  <span className="text-muted-foreground text-xs">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">{Math.floor(ride.duration_seconds / 60)}</span>
                  <span className="text-muted-foreground text-xs">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>
                <span className="text-xs text-muted-foreground">({ride.review_count})</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 Ride
          </Button>
        </CardContent>
      </div>
    </Card>
  );

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

  return (
    <section className="py-16">
      <div className="container mx-auto px-4">
        <Tabs defaultValue="popular-parks" className="w-full">
          <div className="text-center mb-8">
            <TabsList className="grid w-full max-w-4xl mx-auto grid-cols-3 md:grid-cols-6 h-auto p-2 bg-card border border-border/50 rounded-lg shadow-sm">
              <TabsTrigger value="popular-parks" className="text-xs md:text-sm px-2 py-3">
                Popular Parks
              </TabsTrigger>
              <TabsTrigger value="trending-parks" className="text-xs md:text-sm px-2 py-3">
                Trending Parks
              </TabsTrigger>
              <TabsTrigger value="popular-rides" className="text-xs md:text-sm px-2 py-3">
                Popular Rides
              </TabsTrigger>
              <TabsTrigger value="trending-rides" className="text-xs md:text-sm px-2 py-3">
                Trending Rides
              </TabsTrigger>
              <TabsTrigger value="recent-parks" className="text-xs md:text-sm px-2 py-3">
                New Parks
              </TabsTrigger>
              <TabsTrigger value="recent-rides" className="text-xs md:text-sm px-2 py-3">
                New Rides
              </TabsTrigger>
            </TabsList>
          </div>

          <TabsContent value="popular-parks" className="mt-8">
            <div className="text-center mb-6">
              <h2 className="text-2xl font-bold mb-2">Most Popular Parks</h2>
              <p className="text-muted-foreground">Highest rated theme parks worldwide</p>
            </div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6 gap-6">
              {popularParks.map((park) => (
                <ParkCard key={park.id} park={park} />
              ))}
            </div>
          </TabsContent>

          <TabsContent value="trending-parks" className="mt-8">
            <div className="text-center mb-6">
              <h2 className="text-2xl font-bold mb-2">Trending Parks</h2>
              <p className="text-muted-foreground">Most reviewed parks this month</p>
            </div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6 gap-6">
              {trendingParks.map((park) => (
                <ParkCard key={park.id} park={park} />
              ))}
            </div>
          </TabsContent>

          <TabsContent value="popular-rides" className="mt-8">
            <div className="text-center mb-6">
              <h2 className="text-2xl font-bold mb-2">Most Popular Rides</h2>
              <p className="text-muted-foreground">Highest rated attractions worldwide</p>
            </div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6 gap-6">
              {popularRides.map((ride) => (
                <RideCard key={ride.id} ride={ride} />
              ))}
            </div>
          </TabsContent>

          <TabsContent value="trending-rides" className="mt-8">
            <div className="text-center mb-6">
              <h2 className="text-2xl font-bold mb-2">Trending Rides</h2>
              <p className="text-muted-foreground">Most talked about attractions</p>
            </div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6 gap-6">
              {trendingRides.map((ride) => (
                <RideCard key={ride.id} ride={ride} />
              ))}
            </div>
          </TabsContent>

          <TabsContent value="recent-parks" className="mt-8">
            <div className="text-center mb-6">
              <h2 className="text-2xl font-bold mb-2">Recently Added Parks</h2>
              <p className="text-muted-foreground">Latest parks added to our database</p>
            </div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6 gap-6">
              {recentParks.map((park) => (
                <ParkCard key={park.id} park={park} />
              ))}
            </div>
          </TabsContent>

          <TabsContent value="recent-rides" className="mt-8">
            <div className="text-center mb-6">
              <h2 className="text-2xl font-bold mb-2">Recently Added Rides</h2>
              <p className="text-muted-foreground">Latest attractions added to our database</p>
            </div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6 gap-6">
              {recentRides.map((ride) => (
                <RideCard key={ride.id} ride={ride} />
              ))}
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </section>
  );
}