
import React, { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { X } from "lucide-react";
import { toast } from "sonner";
import ProjectBasicFields from "./project-form/ProjectBasicFields";
import ProjectImageUpload from "./project-form/ProjectImageUpload";
import ProjectDeliveryTime from "./project-form/ProjectDeliveryTime";
import ProjectTagsManager from "./project-form/ProjectTagsManager";
import ProjectURLField from "./project-form/ProjectURLField";
import ProjectFormActions from "./project-form/ProjectFormActions";

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

interface ProjectFormProps {
  project?: Project | null;
  onClose: () => void;
}

const ProjectForm = ({ project, onClose }: ProjectFormProps) => {
  const [formData, setFormData] = useState({
    title: project?.title || "",
    category: project?.category || "website" as 'website' | 'ai' | 'webapp',
    description: project?.description || "",
    image: project?.image || "",
    delivery_time: project?.delivery_time || "",
    tags: project?.tags || [],
    project_url: project?.project_url || "",
  });
  const [loading, setLoading] = useState(false);

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

    try {
      if (project) {
        // Update existing project
        const { error } = await supabase
          .from('projects')
          .update({
            title: formData.title,
            category: formData.category,
            description: formData.description,
            image: formData.image,
            delivery_time: formData.delivery_time,
            tags: formData.tags,
            project_url: formData.project_url || null,
            updated_at: new Date().toISOString(),
          })
          .eq('id', project.id);

        if (error) throw error;
        toast.success("Projet mis à jour avec succès");
      } else {
        // Create new project
        const { error } = await supabase
          .from('projects')
          .insert([{
            title: formData.title,
            category: formData.category,
            description: formData.description,
            image: formData.image,
            delivery_time: formData.delivery_time,
            tags: formData.tags,
            project_url: formData.project_url || null,
          }]);

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

      onClose();
    } catch (error) {
      console.error('Error saving project:', 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>
            {project ? "Modifier le projet" : "Nouveau projet"}
          </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">
          <ProjectBasicFields
            title={formData.title}
            category={formData.category}
            description={formData.description}
            onTitleChange={(value) => setFormData(prev => ({ ...prev, title: value }))}
            onCategoryChange={(value) => setFormData(prev => ({ ...prev, category: value }))}
            onDescriptionChange={(value) => setFormData(prev => ({ ...prev, description: value }))}
          />

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

          <ProjectDeliveryTime
            deliveryTime={formData.delivery_time}
            onDeliveryTimeChange={(value) => setFormData(prev => ({ ...prev, delivery_time: value }))}
          />

          <ProjectTagsManager
            tags={formData.tags}
            onTagsChange={(tags) => setFormData(prev => ({ ...prev, tags }))}
          />

          <ProjectURLField
            projectUrl={formData.project_url}
            onProjectUrlChange={(value) => setFormData(prev => ({ ...prev, project_url: value }))}
          />

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

export default ProjectForm;
