import React, { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent } from "@/components/ui/card";
import { toast } from "sonner";
import ProjectForm from "./ProjectForm";
import ProjectsHeader from "./projects-manager/ProjectsHeader";
import ProjectsGrid from "./projects-manager/ProjectsGrid";
import { ProjectCategory } from "./projects-manager/ProjectCategoryFilter";

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

const ProjectsManager = () => {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingProject, setEditingProject] = useState<Project | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState<ProjectCategory | 'all'>('all');

  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);
      toast.error("Erreur lors du chargement des projets");
    } finally {
      setLoading(false);
    }
  };

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

  const handleDelete = async (id: string) => {
    if (!confirm("Êtes-vous sûr de vouloir supprimer ce projet ?")) return;

    try {
      const { error } = await supabase
        .from('projects')
        .delete()
        .eq('id', id);

      if (error) throw error;
      
      toast.success("Projet supprimé avec succès");
      fetchProjects();
    } catch (error) {
      console.error('Error deleting project:', error);
      toast.error("Erreur lors de la suppression");
    }
  };

  const handleMoveUp = async (project: Project) => {
    const currentIndex = projects.findIndex(p => p.id === project.id);
    if (currentIndex === 0) return;

    const previousProject = projects[currentIndex - 1];
    
    try {
      await supabase
        .from('projects')
        .update({ display_order: previousProject.display_order })
        .eq('id', project.id);
      
      await supabase
        .from('projects')
        .update({ display_order: project.display_order })
        .eq('id', previousProject.id);

      toast.success("Ordre modifié avec succès");
      fetchProjects();
    } catch (error) {
      console.error('Error moving project up:', error);
      toast.error("Erreur lors du déplacement");
    }
  };

  const handleMoveDown = async (project: Project) => {
    const currentIndex = projects.findIndex(p => p.id === project.id);
    if (currentIndex === projects.length - 1) return;

    const nextProject = projects[currentIndex + 1];
    
    try {
      await supabase
        .from('projects')
        .update({ display_order: nextProject.display_order })
        .eq('id', project.id);
      
      await supabase
        .from('projects')
        .update({ display_order: project.display_order })
        .eq('id', nextProject.id);

      toast.success("Ordre modifié avec succès");
      fetchProjects();
    } catch (error) {
      console.error('Error moving project down:', error);
      toast.error("Erreur lors du déplacement");
    }
  };

  const handleEdit = (project: Project) => {
    setEditingProject(project);
    setShowForm(true);
  };

  const handleAdd = () => {
    setEditingProject(null);
    setShowForm(true);
  };

  const handleFormClose = () => {
    setShowForm(false);
    setEditingProject(null);
    fetchProjects();
  };

  // Filtrer les projets selon la catégorie sélectionnée
  const filteredProjects = selectedCategory === 'all' 
    ? projects 
    : projects.filter(project => project.category === selectedCategory);

  // Calculer les comptes par catégorie
  const projectCounts = {
    all: projects.length,
    website: projects.filter(p => p.category === 'website').length,
    webapp: projects.filter(p => p.category === 'webapp').length,
    ai: projects.filter(p => p.category === 'ai').length,
  };

  if (loading) {
    return (
      <Card>
        <CardContent className="flex items-center justify-center p-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        </CardContent>
      </Card>
    );
  }

  if (showForm) {
    return (
      <ProjectForm
        project={editingProject}
        onClose={handleFormClose}
      />
    );
  }

  return (
    <div className="space-y-6">
      <ProjectsHeader 
        onAdd={handleAdd}
        selectedCategory={selectedCategory}
        onCategoryChange={setSelectedCategory}
        projectCounts={projectCounts}
      />
      <ProjectsGrid
        projects={filteredProjects}
        onEdit={handleEdit}
        onDelete={handleDelete}
        onMoveUp={handleMoveUp}
        onMoveDown={handleMoveDown}
        onAdd={handleAdd}
      />
    </div>
  );
};

export default ProjectsManager;
