
import React, { useState, useEffect } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { ExternalLink, Globe, Bot, Monitor } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";

interface Project {
  id: string;
  title: string;
  category: 'website' | 'ai' | 'webapp';
  description: string;
  image: string;
  tags: string[];
  delivery_time: string;
  project_url: string | null;
}

const PortfolioSection = () => {
  const [activeFilter, setActiveFilter] = useState("all");
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchProjects = async () => {
      try {
        const { data, error } = await supabase
          .from('projects')
          .select('*')
          .order('display_order', { ascending: true });

        if (error) throw error;
        setProjects((data || []) as Project[]);
      } catch (error) {
        console.error('Error fetching projects:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchProjects();
  }, []);

  const filteredProjects = activeFilter === "all" 
    ? projects 
    : projects.filter(project => project.category === activeFilter);

  const filters = [
    { id: "all", label: "Tous les projets", icon: null },
    { id: "website", label: "Sites Web", icon: Globe },
    { id: "webapp", label: "Web Apps", icon: Monitor },
    { id: "ai", label: "Agents IA", icon: Bot }
  ];

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case 'website':
        return <Globe className="h-4 w-4 text-blue-600" />;
      case 'webapp':
        return <Monitor className="h-4 w-4 text-green-600" />;
      case 'ai':
        return <Bot className="h-4 w-4 text-purple-600" />;
      default:
        return <Globe className="h-4 w-4 text-blue-600" />;
    }
  };

  const getCategoryLabel = (category: string) => {
    switch (category) {
      case 'website':
        return 'Site Web';
      case 'webapp':
        return 'Web App';
      case 'ai':
        return 'Agent IA';
      default:
        return 'Site Web';
    }
  };

  const handleProjectClick = (project: Project) => {
    if (project.project_url) {
      window.open(project.project_url, '_blank', 'noopener,noreferrer');
    }
  };

  if (loading) {
    return (
      <section id="portfolio" className="py-20 bg-gradient-to-b from-purple-100/70 via-blue-100/50 to-indigo-50">
        <div className="container mx-auto px-4">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">Chargement des projets...</p>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section id="portfolio" className="py-20 bg-gradient-to-b from-purple-100/70 via-blue-100/50 to-indigo-50">
      <div className="container mx-auto px-4">
        {/* Header */}
        <div className="text-center max-w-4xl mx-auto mb-16">
          <h2 className="text-4xl md:text-5xl font-bold mb-6 bg-gradient-to-r from-gray-900 to-gray-600 bg-clip-text text-transparent">
            Nos Réalisations
          </h2>
          <p className="text-xl text-gray-600">
            Découvrez quelques-uns de nos projets récents, créés avec passion et innovation
          </p>
        </div>

        {/* Filters */}
        <div className="flex justify-center mb-12">
          <div className="inline-flex bg-white rounded-full p-1 shadow-lg border">
            {filters.map((filter) => {
              const Icon = filter.icon;
              return (
                <Button
                  key={filter.id}
                  onClick={() => setActiveFilter(filter.id)}
                  variant={activeFilter === filter.id ? "default" : "ghost"}
                  className={`rounded-full px-6 py-2 transition-all duration-300 ${
                    activeFilter === filter.id 
                      ? "bg-gradient-to-r from-blue-600 to-purple-600 text-white shadow-md" 
                      : "text-gray-600 hover:text-gray-900"
                  }`}
                >
                  {Icon && <Icon className="w-4 h-4 mr-2" />}
                  {filter.label}
                </Button>
              );
            })}
          </div>
        </div>

        {/* Projects grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
          {filteredProjects.map((project) => (
            <Card key={project.id} className="group hover:shadow-2xl transition-all duration-500 hover:-translate-y-2 border-0 bg-white overflow-hidden">
              <div className="relative overflow-hidden">
                <img 
                  src={project.image} 
                  alt={project.title}
                  className="w-full h-48 object-cover group-hover:scale-110 transition-transform duration-500"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                <div className="absolute top-4 right-4 bg-white/90 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-gray-800">
                  ⚡ {project.delivery_time}
                </div>
              </div>
              
              <CardContent className="p-6">
                <div className="flex items-center justify-between mb-3">
                  <h3 className="text-xl font-bold text-gray-900 group-hover:text-blue-600 transition-colors duration-300">
                    {project.title}
                  </h3>
                  <div className="flex items-center space-x-1">
                    {getCategoryIcon(project.category)}
                    <Badge variant="outline" className="text-xs">
                      {getCategoryLabel(project.category)}
                    </Badge>
                  </div>
                </div>
                <p className="text-gray-600 mb-4 leading-relaxed">{project.description}</p>
                
                <div className="flex flex-wrap gap-2 mb-4">
                  {project.tags.map((tag, index) => (
                    <span key={index} className="px-3 py-1 bg-gradient-to-r from-blue-100 to-purple-100 text-blue-800 text-xs rounded-full">
                      {tag}
                    </span>
                  ))}
                </div>

                {project.project_url && (
                  <Button 
                    variant="outline" 
                    size="sm" 
                    className="w-full group-hover:bg-gradient-to-r group-hover:from-blue-600 group-hover:to-purple-600 group-hover:text-white group-hover:border-transparent transition-all duration-300"
                    onClick={() => handleProjectClick(project)}
                  >
                    Voir le projet
                    <ExternalLink className="w-4 h-4 ml-2" />
                  </Button>
                )}
              </CardContent>
            </Card>
          ))}
        </div>

        {filteredProjects.length === 0 && (
          <div className="text-center py-12">
            <p className="text-gray-500">Aucun projet trouvé pour cette catégorie.</p>
          </div>
        )}
      </div>
    </section>
  );
};

export default PortfolioSection;
