
import React, { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
import { toast } from "sonner";
import TestimonialBasicFields from "./testimonial-form/TestimonialBasicFields";
import TestimonialContent from "./testimonial-form/TestimonialContent";
import TestimonialImageUpload from "./testimonial-form/TestimonialImageUpload";
import TestimonialProject from "./testimonial-form/TestimonialProject";
import TestimonialFormActions from "./testimonial-form/TestimonialFormActions";

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;
}

interface TestimonialFormProps {
  testimonial?: Testimonial | null;
  onClose: () => void;
}

const TestimonialForm = ({ testimonial, onClose }: TestimonialFormProps) => {
  const [formData, setFormData] = useState({
    name: testimonial?.name || "",
    role: testimonial?.role || "",
    company: testimonial?.company || "",
    quote: testimonial?.quote || "",
    rating: testimonial?.rating || 5,
    image: testimonial?.image || "",
    project: testimonial?.project || "",
  });
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      if (testimonial) {
        // Update existing testimonial - don't modify display_order
        const { error } = await supabase
          .from('testimonials')
          .update({
            name: formData.name,
            role: formData.role,
            company: formData.company,
            quote: formData.quote,
            rating: formData.rating,
            image: formData.image,
            project: formData.project || null,
            updated_at: new Date().toISOString(),
          })
          .eq('id', testimonial.id);

        if (error) throw error;
        toast.success("Témoignage mis à jour avec succès");
      } else {
        // Create new testimonial - get the next display_order
        const { data: existingTestimonials, error: fetchError } = await supabase
          .from('testimonials')
          .select('display_order')
          .order('display_order', { ascending: false })
          .limit(1);

        if (fetchError) throw fetchError;

        const nextDisplayOrder = existingTestimonials && existingTestimonials.length > 0 
          ? existingTestimonials[0].display_order + 1 
          : 1;

        const { error } = await supabase
          .from('testimonials')
          .insert([{
            name: formData.name,
            role: formData.role,
            company: formData.company,
            quote: formData.quote,
            rating: formData.rating,
            image: formData.image,
            project: formData.project || null,
            display_order: nextDisplayOrder,
          }]);

        if (error) throw error;
        toast.success("Témoignage créé avec succès");
      }

      onClose();
    } catch (error) {
      console.error('Error saving testimonial:', error);
      toast.error("Erreur lors de la sauvegarde");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card className="max-w-2xl mx-auto">
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle>
            {testimonial ? "Modifier le témoignage" : "Nouveau témoignage"}
          </CardTitle>
          <Button variant="ghost" size="sm" onClick={onClose}>
            <X className="h-4 w-4" />
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          <TestimonialBasicFields
            name={formData.name}
            role={formData.role}
            company={formData.company}
            onNameChange={(value) => setFormData(prev => ({ ...prev, name: value }))}
            onRoleChange={(value) => setFormData(prev => ({ ...prev, role: value }))}
            onCompanyChange={(value) => setFormData(prev => ({ ...prev, company: value }))}
          />

          <TestimonialContent
            quote={formData.quote}
            rating={formData.rating}
            onQuoteChange={(value) => setFormData(prev => ({ ...prev, quote: value }))}
            onRatingChange={(rating) => setFormData(prev => ({ ...prev, rating }))}
          />

          <TestimonialImageUpload
            image={formData.image}
            onImageChange={(value) => setFormData(prev => ({ ...prev, image: value }))}
          />

          <TestimonialProject
            project={formData.project}
            onProjectChange={(value) => setFormData(prev => ({ ...prev, project: value }))}
          />

          <TestimonialFormActions
            loading={loading}
            isEdit={!!testimonial}
            onCancel={onClose}
          />
        </form>
      </CardContent>
    </Card>
  );
};

export default TestimonialForm;
