import { useState, useEffect } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ParkCard } from '@/components/parks/ParkCard';
import { RideCard } from '@/components/rides/RideCard';
import { RecentChangeCard } from './RecentChangeCard';
import { Badge } from '@/components/ui/badge';
import { Park, Ride, ActivityEntry } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';

export function ContentTabs() {
  const [trendingParks, setTrendingParks] = useState<Park[]>([]);
  const [trendingRides, setTrendingRides] = useState<Ride[]>([]);
  const [recentParks, setRecentParks] = useState<Park[]>([]);
  const [recentRides, setRecentRides] = useState<Ride[]>([]);
  const [recentChanges, setRecentChanges] = useState<ActivityEntry[]>([]);
  const [recentlyOpened, setRecentlyOpened] = useState<Array<(Park | Ride) & { entityType: 'park' | 'ride' }>>([]);
  const [loading, setLoading] = useState(true);

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

  const fetchContent = async () => {
    try {
      // Trending Parks (by 30-day view count)
      const { data: trending } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .order('view_count_30d', { 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);

      // Trending Rides (by 30-day view count)
      const { data: trendingRidesData } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .order('view_count_30d', { 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);

      // Recent changes will be populated from other sources since entity_versions requires auth
      const changesData: ActivityEntry[] = [];

      // Process changes to extract entity info from version_data
      const processedChanges: ActivityEntry[] = [];

      // Fetch recently opened parks and rides
      const oneYearAgo = new Date();
      oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
      const dateThreshold = oneYearAgo.toISOString().split('T')[0];

      const { data: openedParks } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .not('opening_date', 'is', null)
        .gte('opening_date', dateThreshold)
        .order('opening_date', { ascending: false })
        .limit(20);

      const { data: openedRides } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .not('opening_date', 'is', null)
        .gte('opening_date', dateThreshold)
        .order('opening_date', { ascending: false })
        .limit(20);

      // Combine and sort by opening date
      const combinedOpened = [
        ...(openedParks || []).map(p => ({ ...p, entityType: 'park' as const })),
        ...(openedRides || []).map(r => ({ ...r, entityType: 'ride' as const }))
      ]
        .sort((a, b) => new Date(b.opening_date).getTime() - new Date(a.opening_date).getTime())
        .slice(0, 24);

      setTrendingParks(trending || []);
      setRecentParks(recent || []);
      setTrendingRides(trendingRidesData || []);
      setRecentRides(recentRidesData || []);
      setRecentChanges(processedChanges);
      setRecentlyOpened(combinedOpened);
    } catch (error) {
      console.error('Error fetching content:', error);
    } finally {
      setLoading(false);
    }
  };


  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-8">
      <div className="container mx-auto px-4">
        <Tabs defaultValue="trending-parks" className="w-full">
          <div className="text-center mb-8">
            <TabsList className="grid w-full max-w-5xl mx-auto grid-cols-3 md:grid-cols-6 h-auto p-2 bg-gradient-to-r from-primary/10 via-secondary/10 to-accent/10 dark:from-primary/20 dark:via-secondary/20 dark:to-accent/20 dark:bg-card/50 border border-primary/20 dark:border-primary/30 rounded-xl shadow-lg backdrop-blur-sm">
              <TabsTrigger value="trending-parks" className="text-xs md:text-sm px-2 py-3">
                Trending Parks
              </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>
              <TabsTrigger value="recent-changes" className="text-xs md:text-sm px-2 py-3">
                Recent Changes
              </TabsTrigger>
              <TabsTrigger value="recently-opened" className="text-xs md:text-sm px-2 py-3">
                Recently Opened
              </TabsTrigger>
            </TabsList>
          </div>

      <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 viewed parks in the last 30 days</p>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
          {trendingParks.map((park) => (
            <ParkCard key={park.id} park={park} />
          ))}
        </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 viewed rides in the last 30 days</p>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
          {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 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
          {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 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
          {recentRides.map((ride) => (
            <RideCard key={ride.id} ride={ride} />
          ))}
        </div>
      </TabsContent>

      <TabsContent value="recent-changes" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl font-bold mb-2">Recent Changes</h2>
          <p className="text-muted-foreground">Latest updates across all entities</p>
        </div>
        <div className="text-center py-8 text-muted-foreground">
          No recent changes to display
        </div>
      </TabsContent>

      <TabsContent value="recently-opened" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl font-bold mb-2">Recently Opened</h2>
          <p className="text-muted-foreground">Parks and rides that opened in the last year</p>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
          {recentlyOpened.map((entity: any) => (
            entity.entityType === 'park' ? (
              <div key={entity.id} className="relative">
                <ParkCard park={entity} />
                <Badge className="absolute top-2 right-2 bg-green-500/90 text-white backdrop-blur-sm">
                  {new Date(entity.opening_date).getFullYear()}
                </Badge>
              </div>
            ) : (
              <div key={entity.id} className="relative">
                <RideCard ride={entity} />
                <Badge className="absolute top-2 right-2 bg-green-500/90 text-white backdrop-blur-sm">
                  {new Date(entity.opening_date).getFullYear()}
                </Badge>
              </div>
            )
          ))}
        </div>
      </TabsContent>
        </Tabs>
      </div>
    </section>
  );
}