import { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; 
import { ArrowRight, BookOpen, Users, Clock } from "lucide-react";
import { Link } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/hooks/useAuth";
import { LoadingSpinner } from "@/components/ui/loading-spinner";

interface WikiPage {
  id: string;
  title: string;
  slug: string;
  content: string;
  tags: string[];
  updated_at: string;
  category?: {
    name: string;
    icon: string;
  };
}

interface TeamMember {
  user_id: string;
  username: string;
  avatar_url: string | null;
  total_activities: number;
  contributions: number;
  page_edits: number;
  last_activity: string | null;
  function: string | null;
  function_color: string | null;
}

interface WikiCategory {
  id: string;
  name: string;
  icon: string;
  description: string;
  pages: {
    id: string;
    title: string;
    slug: string;
    content: string;
    tags: string[];
    updated_at: string;
  }[];
}

const WikiHomePage = () => {
  const { user, profile } = useAuth();
  const [categories, setCategories] = useState<WikiCategory[]>([]);
  const [recentPages, setRecentPages] = useState<WikiPage[]>([]);
  const [teamMembers, setTeamMembers] = useState<TeamMember[]>([]);
  const [stats, setStats] = useState({ totalPages: 0, totalCategories: 0 });
  const [loading, setLoading] = useState(true);

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

  const fetchData = async () => {
    try {
      setLoading(true);
      
      const { data: categoriesData, error: categoriesError } = await supabase
        .from('categories')
        .select(`
          *,
          pages:pages(id, title, slug, content, tags, updated_at)
        `)
        .eq('is_active', true)
        .order('order_index');

      if (categoriesError) throw categoriesError;

      const formattedCategories = categoriesData?.map(category => ({
        ...category,
        pages: (category.pages || []).filter(page => page.id)
      })) || [];

      const { data: pagesData, error: pagesError } = await supabase
        .from('pages')
        .select(`
          *,
          category:categories(name, icon)
        `)
        .eq('is_published', true)
        .order('updated_at', { ascending: false })
        .limit(6);

      if (pagesError) throw pagesError;

      const formattedPages = pagesData?.map(page => ({
        ...page,
        category: page.category
      })) || [];

      const { data: profilesData, error: profilesError } = await supabase
        .from('profiles')
        .select('user_id, username, avatar_url, function, function_color')
        .eq('is_active', true)
        .in('role', ['admin', 'contributor', 'supervizor']);

      if (profilesError) {
        console.error('Error fetching profiles:', profilesError);
      }

      const { data: activityData, error: activityError } = await supabase
        .rpc('get_contributor_stats', { days_period: 90 });

      if (activityError) {
        console.error('Error fetching activity data:', activityError);
      }

      const formattedTeamMembers = (activityData || [])
        .map((activity: any) => {
          const profile = profilesData?.find(p => p.user_id === activity.user_id);
          return {
            ...activity,
            function: profile?.function,
            function_color: profile?.function_color
          };
        })
        .slice(0, 9); 

      setCategories(formattedCategories);
      setRecentPages(formattedPages);
      setTeamMembers(formattedTeamMembers);
      
      const totalPages = formattedCategories.reduce((acc, cat) => acc + cat.pages.length, 0);
      setStats({
        totalPages,
        totalCategories: formattedCategories.length
      });
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-8">
      <div className="text-center py-12">
        <div className="inline-flex items-center justify-center w-20 h-20 rounded-full mb-6 glass-container">
          <img src="https://i.postimg.cc/pdzXBW35/logo-icon.png" alt="Logo"></img>

        </div>
        <h1 className="text-4xl font-bold mb-4" style={{ color: '#306C0B' }}>
          Welcome to RAGE:MP B-HOOD Wikipedia
        </h1>
        <p className="text-xl text-foreground max-w-3xl mx-auto leading-relaxed mb-8">
          📚 Bine ai venit pe Wiki-ul oficial al serverului! 
          Folosește meniul din stânga pentru a explora ghiduri și sisteme. 
          Caută rapid informații folosind bara de căutare de sus sau navighează prin categorii.
          <br />
          <strong className="text-white">Totul este organizat pentru a te ajuta să găsești informația dorită! 🎮</strong>
        </p>
        <div className="flex gap-4 justify-center mt-8">
          <Button size="lg" variant="default" asChild>
            <Link to="/page/ghidul-nceptorului">
              Get Started
              <ArrowRight className="ml-2 h-4 w-4" />
            </Link>
          </Button>
          {profile?.role === 'admin' && (
            <Button variant="outline" size="lg" asChild>
              <Link to="/admin">
                Admin Panel
              </Link>
            </Button>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-12">
        <div className="glass-container p-6 text-center">
          <BookOpen className="w-8 h-8 text-primary mx-auto mb-2" />
          <div className="text-2xl font-bold text-white">
            {loading ? "..." : stats.totalPages}
          </div>
          <div className="text-sm text-foreground/80">Total Pages</div>
        </div>
        <div className="glass-container p-6 text-center">
          <Users className="w-8 h-8 text-primary mx-auto mb-2" />
          <div className="text-2xl font-bold text-white">
            {loading ? "..." : stats.totalCategories}
          </div>
          <div className="text-sm text-foreground/80">Categories</div>
        </div>
        <div className="glass-container p-6 text-center">
          <Clock className="w-8 h-8 text-primary mx-auto mb-2" />
          <div className="text-2xl font-bold text-white">24/7</div>
          <div className="text-sm text-foreground/80">Available</div>
        </div>
      </div>

      <section>
        <h2 className="text-2xl font-bold mb-6" style={{ color: '#1B7C38' }}>Recently Updated</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {loading ? (
            <div className="text-center py-8">
              <LoadingSpinner />
              <p className="text-muted-foreground mt-2">Loading recent pages...</p>
            </div>
          ) : recentPages.length > 0 ? (
            recentPages.map((page) => (
              <div key={page.id} className="glass-container p-4 hover:shadow-glow transition-all duration-300">
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-sm text-primary font-medium">
                        {page.category?.name}
                      </span>
                      <span className="text-sm">{page.category?.icon}</span>
                    </div>
                    <h3 className="font-medium text-white mb-1 truncate">
                      {page.title}
                    </h3>
                    <p className="text-sm text-foreground/80">
                      Updated on {new Date(page.updated_at).toLocaleString('ro-RO', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit', 
                        minute: '2-digit'
                      })}
                    </p>
                    <div className="flex flex-wrap gap-1 mt-2">
                      {page.tags?.slice(0, 2).map((tag) => (
                        <Badge key={tag} variant="outline" className="text-xs border-primary/30 text-primary-glow">
                          {tag}
                        </Badge>
                      ))}
                    </div>
                  </div>
                  <Button variant="new" size="sm" asChild>
                    <Link to={`/page/${page.slug}`}>
                      <p className="text-white">Explorează</p>
                      <ArrowRight className="h-3 w-3" />
                    </Link>
                  </Button>
                </div>
              </div>
            ))
          ) : (
            <div className="col-span-full text-center py-8">
              <p className="text-muted-foreground">No recent pages found.</p>
            </div>
          )}
        </div>
      </section>
      <section>
        <h2 className="text-2xl font-bold mb-6" style={{ color: '#1B7C38' }}>Our Team</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {loading ? (
            <div className="text-center py-8">
              <LoadingSpinner />
              <p className="text-muted-foreground mt-2">Loading team members...</p>
            </div>
          ) : teamMembers.length > 0 ? (
            teamMembers.map((member) => (
              <div key={member.user_id} className="glass-container p-4 hover:shadow-glow transition-all duration-300">
                <div className="flex items-center gap-3 mb-3">
                  <Avatar className="h-12 w-12">
                    <AvatarImage src={member.avatar_url} alt={member.username} />
                    <AvatarFallback className="bg-primary/20 text-primary">
                      {member.username?.charAt(0).toUpperCase()}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <h3 className="font-medium text-white truncate">{member.username}</h3>
                      {member.function && (
                        <Badge 
                          className="text-xs px-2 py-1 shrink-0 border-0"
                          style={{ 
                            backgroundColor: member.function_color || '#1B7C38',
                            color: 'white',
                            borderColor: 'transparent'
                          }}
                        >
                          {member.function}
                        </Badge>
                      )}
                    </div>
                    <p className="text-sm text-foreground/80">
                      {member.last_activity ? 
                        `Last activity on ${new Date(member.last_activity).toLocaleDateString('ro-RO')}` :
                        'No recent activity'
                      }
                    </p>
                  </div>
                </div>
                <div className="flex justify-between text-center">
                  <div>
                    <div className="text-lg font-bold text-primary">{member.contributions || 0}</div>
                    <div className="text-xs text-foreground/80">Contributions</div>
                  </div>
                  <div>
                    <div className="text-lg font-bold text-success">{member.page_edits || 0}</div>
                    <div className="text-xs text-foreground/80">Edits</div>
                  </div>
                  <div>
                    <div className="text-lg font-bold text-info">{member.total_activities || 0}</div>
                    <div className="text-xs text-foreground/80">Total</div>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="col-span-full text-center py-8">
              <p className="text-muted-foreground">No team members found.</p>
            </div>
          )}
        </div>
      </section>

    </div>
  );
};

export default WikiHomePage;