
import React, { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Pencil, Trash2, Plus, Star, ArrowUp, ArrowDown } from "lucide-react";
import { toast } from "sonner";
import TestimonialForm from "./TestimonialForm";

interface Testimonial {
  id: string;
  name: string;
  role: string;
  company: string;
  quote: string;
  rating: number;
  image: string;
  project: string | null;
  display_order: number;
  created_at: string;
}

const TestimonialsManager = () => {
  const [testimonials, setTestimonials] = useState<Testimonial[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingTestimonial, setEditingTestimonial] = useState<Testimonial | null>(null);
  const [showForm, setShowForm] = useState(false);

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

      if (error) throw error;
      setTestimonials(data || []);
    } catch (error) {
      console.error('Error fetching testimonials:', error);
      toast.error("Erreur lors du chargement des témoignages");
    } finally {
      setLoading(false);
    }
  };

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

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

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

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

  const handleMoveUp = async (testimonial: Testimonial) => {
    const currentIndex = testimonials.findIndex(t => t.id === testimonial.id);
    if (currentIndex === 0) return; // Already at top

    const previousTestimonial = testimonials[currentIndex - 1];
    
    try {
      // Swap display_order values
      await supabase
        .from('testimonials')
        .update({ display_order: previousTestimonial.display_order })
        .eq('id', testimonial.id);
      
      await supabase
        .from('testimonials')
        .update({ display_order: testimonial.display_order })
        .eq('id', previousTestimonial.id);

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

  const handleMoveDown = async (testimonial: Testimonial) => {
    const currentIndex = testimonials.findIndex(t => t.id === testimonial.id);
    if (currentIndex === testimonials.length - 1) return; // Already at bottom

    const nextTestimonial = testimonials[currentIndex + 1];
    
    try {
      // Swap display_order values
      await supabase
        .from('testimonials')
        .update({ display_order: nextTestimonial.display_order })
        .eq('id', testimonial.id);
      
      await supabase
        .from('testimonials')
        .update({ display_order: testimonial.display_order })
        .eq('id', nextTestimonial.id);

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

  const handleEdit = (testimonial: Testimonial) => {
    setEditingTestimonial(testimonial);
    setShowForm(true);
  };

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

  const handleFormClose = () => {
    setShowForm(false);
    setEditingTestimonial(null);
    fetchTestimonials();
  };

  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 (
      <TestimonialForm
        testimonial={editingTestimonial}
        onClose={handleFormClose}
      />
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-bold">Gestion des Témoignages</h2>
        <Button onClick={handleAdd}>
          <Plus className="h-4 w-4 mr-2" />
          Ajouter un témoignage
        </Button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {testimonials.map((testimonial, index) => (
          <Card key={testimonial.id}>
            <CardHeader>
              <div className="flex items-start justify-between">
                <div className="flex items-center space-x-3">
                  <img
                    src={testimonial.image}
                    alt={testimonial.name}
                    className="w-12 h-12 rounded-full object-cover"
                  />
                  <div>
                    <CardTitle className="text-lg">{testimonial.name}</CardTitle>
                    <p className="text-sm text-gray-600">
                      {testimonial.role}, {testimonial.company}
                    </p>
                  </div>
                </div>
                <div className="flex items-center space-x-1">
                  {[...Array(testimonial.rating)].map((_, i) => (
                    <Star key={i} className="w-4 h-4 text-yellow-400 fill-current" />
                  ))}
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <blockquote className="text-sm text-gray-700 mb-4 italic">
                "{testimonial.quote}"
              </blockquote>
              
              <div className="flex items-center justify-between mb-3">
                {testimonial.project && (
                  <Badge variant="outline" className="text-xs">
                    {testimonial.project}
                  </Badge>
                )}
              </div>

              <div className="flex items-center justify-between">
                <div className="flex space-x-1">
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleMoveUp(testimonial)}
                    disabled={index === 0}
                    className="p-1"
                  >
                    <ArrowUp className="h-3 w-3" />
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleMoveDown(testimonial)}
                    disabled={index === testimonials.length - 1}
                    className="p-1"
                  >
                    <ArrowDown className="h-3 w-3" />
                  </Button>
                </div>
                <div className="flex space-x-2">
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleEdit(testimonial)}
                  >
                    <Pencil className="h-3 w-3" />
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleDelete(testimonial.id)}
                    className="text-red-600 hover:text-red-700"
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {testimonials.length === 0 && (
        <Card>
          <CardContent className="text-center py-8">
            <p className="text-gray-500 mb-4">Aucun témoignage trouvé</p>
            <Button onClick={handleAdd}>
              <Plus className="h-4 w-4 mr-2" />
              Ajouter le premier témoignage
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default TestimonialsManager;
