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 } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { getErrorMessage } from '@/lib/errorHandler';
import { logger } from '@/lib/logger';

interface RecentChange {
  entityType: 'park' | 'ride' | 'company';
  entityId: string;
  entityName: string;
  entitySlug: string;
  parkSlug?: string;
  imageUrl: string | null;
  changeType: string;
  changedAt: string;
  changedByUsername?: string | null;
  changedByAvatar?: string | null;
  changeReason: string | null;
}

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<RecentChange[]>([]);
  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);

      // Fetch recent park versions
      const { data: parkVersions } = await supabase
        .from('park_versions')
        .select(`
          version_id,
          park_id,
          name,
          slug,
          change_type,
          created_at,
          created_by,
          change_reason,
          card_image_url,
          profiles:profiles!park_versions_created_by_fkey(username, avatar_url)
        `)
        .eq('is_current', true)
        .order('created_at', { ascending: false })
        .limit(12);

      // Fetch recent ride versions with park slug for proper routing
      const { data: rideVersions } = await supabase
        .from('ride_versions')
        .select(`
          version_id,
          ride_id,
          name,
          slug,
          change_type,
          created_at,
          created_by,
          change_reason,
          card_image_url,
          park_id,
          profiles:profiles!ride_versions_created_by_fkey(username, avatar_url)
        `)
        .eq('is_current', true)
        .order('created_at', { ascending: false })
        .limit(12);

      // Fetch park slugs for rides that have a park_id
      const rideParksMap = new Map<string, string>();
      if (rideVersions) {
        const parkIds = [...new Set(rideVersions.map(v => v.park_id).filter(Boolean))];
        if (parkIds.length > 0) {
          const { data: parks } = await supabase
            .from('parks')
            .select('id, slug')
            .in('id', parkIds);
          
          parks?.forEach(park => {
            rideParksMap.set(park.id, park.slug);
          });
        }
      }

      // Fetch recent company versions
      const { data: companyVersions } = await supabase
        .from('company_versions')
        .select(`
          version_id,
          company_id,
          name,
          slug,
          change_type,
          created_at,
          created_by,
          change_reason,
          card_image_url,
          profiles:profiles!company_versions_created_by_fkey(username, avatar_url)
        `)
        .eq('is_current', true)
        .order('created_at', { ascending: false })
        .limit(12);

      // Combine all changes into a unified structure
      const allChanges: RecentChange[] = [
        ...(parkVersions || []).map(v => ({
          entityType: 'park' as const,
          entityId: v.park_id,
          entityName: v.name,
          entitySlug: v.slug,
          imageUrl: v.card_image_url,
          changeType: v.change_type,
          changedAt: v.created_at,
          changedByUsername: v.profiles?.username,
          changedByAvatar: v.profiles?.avatar_url,
          changeReason: v.change_reason,
        })),
        ...(rideVersions || []).map(v => ({
          entityType: 'ride' as const,
          entityId: v.ride_id,
          entityName: v.name,
          entitySlug: v.slug,
          parkSlug: v.park_id ? rideParksMap.get(v.park_id) : undefined,
          imageUrl: v.card_image_url,
          changeType: v.change_type,
          changedAt: v.created_at,
          changedByUsername: v.profiles?.username,
          changedByAvatar: v.profiles?.avatar_url,
          changeReason: v.change_reason,
        })),
        ...(companyVersions || []).map(v => ({
          entityType: 'company' as const,
          entityId: v.company_id,
          entityName: v.name,
          entitySlug: v.slug,
          imageUrl: v.card_image_url,
          changeType: v.change_type,
          changedAt: v.created_at,
          changedByUsername: v.profiles?.username,
          changedByAvatar: v.profiles?.avatar_url,
          changeReason: v.change_reason,
        }))
      ]
        .sort((a, b) => new Date(b.changedAt).getTime() - new Date(a.changedAt).getTime())
        .slice(0, 24);

      // 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(allChanges);
      setRecentlyOpened(combinedOpened);
    } catch (error: unknown) {
      logger.error('Failed to fetch content', { error: getErrorMessage(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>
        {recentChanges.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4">
            {recentChanges.map((change) => (
              <RecentChangeCard
                key={`${change.entityType}-${change.entityId}-${change.changedAt}`}
                entityType={change.entityType}
                entityId={change.entityId}
                entityName={change.entityName}
                entitySlug={change.entitySlug}
                parkSlug={change.parkSlug}
                imageUrl={change.imageUrl}
                changeType={change.changeType}
                changedAt={change.changedAt}
                changedByUsername={change.changedByUsername}
                changedByAvatar={change.changedByAvatar}
                changeReason={change.changeReason}
              />
            ))}
          </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>
  );
}