{% extends 'base.html.twig' %}

{% block title %}Ajouter un produit - Marketplace{% endblock %}

{% block body %}
<div class="container mx-auto px-4 py-8">
    <div class="max-w-4xl mx-auto">
        <div class="flex items-center mb-6">
            <a href="{{ path('vendor_products') }}" class="text-gray-600 hover:text-gray-900 mr-4">
                <i class="fas fa-arrow-left text-xl"></i>
            </a>
            <h1 class="text-2xl font-bold">Ajouter un produit</h1>
        </div>
        
        <div class="bg-white rounded-lg shadow overflow-hidden" x-data="productForm()" x-init="init()">
            <form @submit.prevent="submitProduct" method="POST" enctype="multipart/form-data" class="p-6 space-y-6">
                <!-- Messages d'erreur globaux -->
                <div x-show="errors.global" x-cloak class="bg-red-50 border-l-4 border-red-500 p-4 rounded">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                        <span class="text-red-700" x-text="errors.global"></span>
                    </div>
                </div>
                
                <!-- Informations générales -->
                <div>
                    <h2 class="text-lg font-semibold mb-4">Informations générales</h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- Nom du produit -->
                        <div>
                            <label class="block text-sm font-medium mb-1">
                                Nom du produit <span class="text-red-500">*</span>
                            </label>
                            <input type="text" 
                                   x-model="form.name"
                                   @input="validateField('name')"
                                   class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500"
                                   :class="{'border-red-500': errors.name, 'border-green-500': valid.name}">
                            <p class="text-xs text-gray-500 mt-1">Minimum 3 caractères, maximum 255</p>
                            <p x-show="errors.name" x-text="errors.name" class="text-red-500 text-xs mt-1"></p>
                        </div>
                        
                        <!-- Catégorie -->
                        <div>
                            <label class="block text-sm font-medium mb-1">
                                Catégorie <span class="text-red-500">*</span>
                            </label>
                            <select x-model="form.category" 
                                    @change="validateField('category')"
                                    class="w-full border rounded-lg px-3 py-2"
                                    :class="{'border-red-500': errors.category}">
                                <option value="">Sélectionner une catégorie</option>
                                {% for category in categories %}
                                    <option value="{{ category.id }}">{{ category.name }}</option>
                                {% endfor %}
                            </select>
                            <p x-show="errors.category" x-text="errors.category" class="text-red-500 text-xs mt-1"></p>
                        </div>
                    </div>
                    
                    <!-- Description -->
                    <div class="mt-4">
                        <label class="block text-sm font-medium mb-1">
                            Description <span class="text-red-500">*</span>
                        </label>
                        <textarea x-model="form.description"
                                  @input="validateField('description')"
                                  rows="5"
                                  class="w-full border rounded-lg px-3 py-2"
                                  :class="{'border-red-500': errors.description}"></textarea>
                        <div class="flex justify-between text-xs mt-1">
                            <p class="text-gray-500">Description détaillée du produit</p>
                            <p class="text-gray-500" :class="{'text-red-500': form.description.length < 20}">
                                <span x-text="form.description.length"></span> / 2000 caractères
                            </p>
                        </div>
                        <p x-show="errors.description" x-text="errors.description" class="text-red-500 text-xs mt-1"></p>
                    </div>
                </div>
                
                <!-- Prix et stock -->
                <div>
                    <h2 class="text-lg font-semibold mb-4">Prix et stock</h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <!-- Prix -->
                        <div>
                            <label class="block text-sm font-medium mb-1">
                                Prix (€) <span class="text-red-500">*</span>
                            </label>
                            <input type="number" 
                                   x-model="form.price"
                                   @input="validateField('price')"
                                   step="0.01"
                                   class="w-full border rounded-lg px-3 py-2"
                                   :class="{'border-red-500': errors.price}">
                            <p x-show="errors.price" x-text="errors.price" class="text-red-500 text-xs mt-1"></p>
                        </div>
                        
                        <!-- Prix barré -->
                        <div>
                            <label class="block text-sm font-medium mb-1">Prix barré (€)</label>
                            <input type="number" 
                                   x-model="form.compareAtPrice"
                                   @input="validateField('compareAtPrice')"
                                   step="0.01"
                                   class="w-full border rounded-lg px-3 py-2"
                                   :class="{'border-yellow-500': form.compareAtPrice && form.compareAtPrice <= form.price}">
                            <p x-show="form.compareAtPrice && form.compareAtPrice <= form.price" 
                               class="text-yellow-500 text-xs mt-1">
                                ⚠️ Le prix barré doit être supérieur au prix normal
                            </p>
                        </div>
                        
                        <!-- Stock -->
                        <div>
                            <label class="block text-sm font-medium mb-1">
                                Stock <span class="text-red-500">*</span>
                            </label>
                            <input type="number" 
                                   x-model="form.stock"
                                   @input="validateField('stock')"
                                   class="w-full border rounded-lg px-3 py-2"
                                   :class="{'border-red-500': errors.stock}">
                            <p x-show="errors.stock" x-text="errors.stock" class="text-red-500 text-xs mt-1"></p>
                            <p x-show="form.stock < 5 && form.stock > 0" class="text-yellow-500 text-xs mt-1">
                                ⚠️ Stock faible
                            </p>
                        </div>
                    </div>
                </div>
                
                <!-- Livraison -->
                <div>
                    <h2 class="text-lg font-semibold mb-4">Livraison</h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- Poids -->
                        <div>
                            <label class="block text-sm font-medium mb-1">Poids (kg)</label>
                            <input type="number" 
                                   x-model="form.weight"
                                   @input="validateField('weight')"
                                   step="0.1"
                                   class="w-full border rounded-lg px-3 py-2">
                            <p class="text-xs text-gray-500 mt-1">Utilisé pour calculer les frais de port</p>
                        </div>
                        
                        <!-- Dimensions -->
                        <div>
                            <label class="block text-sm font-medium mb-1">Dimensions (L x l x h cm)</label>
                            <input type="text" 
                                   x-model="form.dimensions"
                                   placeholder="30 x 20 x 10"
                                   class="w-full border rounded-lg px-3 py-2">
                            <p class="text-xs text-gray-500 mt-1">Format: L x l x h</p>
                        </div>
                    </div>
                </div>
                
                <!-- Images -->
                <div>
                    <h2 class="text-lg font-semibold mb-4">Images du produit</h2>
                    
                    <!-- Zone de drop -->
                    <div @dragover.prevent="dragover = true"
                         @dragleave.prevent="dragover = false"
                         @drop.prevent="handleDrop"
                         @click="$refs.fileInput.click()"
                         class="border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition"
                         :class="{'border-primary-500 bg-primary-50': dragover, 'border-gray-300 hover:border-primary-500': !dragover}">
                        <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-2"></i>
                        <p class="text-gray-600">Glissez-déposez vos images ici ou cliquez pour sélectionner</p>
                        <p class="text-xs text-gray-400 mt-1">PNG, JPG, JPEG jusqu'à 5MB (Max 10 images)</p>
                        <input type="file" 
                               x-ref="fileInput"
                               @change="handleFileSelect"
                               multiple 
                               accept="image/*" 
                               class="hidden">
                    </div>
                    
                    <!-- Aperçu des images -->
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4">
                        <template x-for="(image, index) in images" :key="index">
                            <div class="relative group">
                                <img :src="image.preview" class="w-full h-32 object-cover rounded-lg">
                                <button type="button" 
                                        @click="removeImage(index)"
                                        class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center opacity-0 group-hover:opacity-100 transition">
                                    <i class="fas fa-times text-xs"></i>
                                </button>
                                <div x-show="image.error" 
                                     class="absolute bottom-0 left-0 right-0 bg-red-500 text-white text-xs text-center py-1 rounded-b-lg">
                                    <span x-text="image.error"></span>
                                </div>
                            </div>
                        </template>
                    </div>
                    
                    <!-- Message erreur images -->
                    <p x-show="errors.images" x-text="errors.images" class="text-red-500 text-xs mt-2"></p>
                </div>
                
                <!-- Attributs -->
                <div>
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-lg font-semibold">Attributs</h2>
                        <button type="button" 
                                @click="addAttribute"
                                class="text-primary-600 hover:text-primary-700">
                            <i class="fas fa-plus mr-1"></i> Ajouter un attribut
                        </button>
                    </div>
                    
                    <div class="space-y-2">
                        <template x-for="(attr, index) in attributes" :key="index">
                            <div class="flex gap-2">
                                <input type="text" 
                                       x-model="attr.name"
                                       placeholder="Nom (ex: Couleur)"
                                       class="flex-1 border rounded-lg px-3 py-2">
                                <input type="text" 
                                       x-model="attr.value"
                                       placeholder="Valeur (ex: Rouge)"
                                       class="flex-1 border rounded-lg px-3 py-2">
                                <button type="button" 
                                        @click="removeAttribute(index)"
                                        class="text-red-500 hover:text-red-700 px-3">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </template>
                    </div>
                </div>
                
                <!-- Boutons d'action -->
                <div class="bg-gray-50 -mx-6 -mb-6 px-6 py-4 flex justify-end space-x-3 rounded-b-lg">
                    <button type="button" 
                            onclick="window.history.back()"
                            class="px-4 py-2 border rounded-lg hover:bg-gray-100 transition">
                        Annuler
                    </button>
                    <button type="submit" 
                            :disabled="!isValid || isSubmitting"
                            class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fas fa-spinner fa-spin mr-2" x-show="isSubmitting" x-cloak></i>
                        <span x-show="!isSubmitting">Publier le produit</span>
                        <span x-show="isSubmitting">Publication en cours...</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function productForm() {
        return {
            // Formulaire
            form: {
                name: '',
                category: '',
                description: '',
                price: '',
                compareAtPrice: '',
                stock: '',
                weight: '',
                dimensions: ''
            },
            
            // État
            images: [],
            attributes: [],
            isSubmitting: false,
            dragover: false,
            
            // Validation
            errors: {
                global: '',
                name: '',
                category: '',
                description: '',
                price: '',
                stock: '',
                images: ''
            },
            
            valid: {
                name: false,
                category: false,
                description: false,
                price: false,
                stock: false
            },
            
            // Initialisation
            init() {
                // Ajouter un attribut par défaut
                this.addAttribute();
                
                // Observer les changements pour la validation globale
                this.$watch('form', () => this.validateAll());
                this.$watch('images', () => this.validateImages());
            },
            
            // Validation d'un champ spécifique
            validateField(field) {
                switch(field) {
                    case 'name':
                        if (!this.form.name.trim()) {
                            this.errors.name = 'Le nom du produit est requis';
                            this.valid.name = false;
                        } else if (this.form.name.length < 3) {
                            this.errors.name = 'Le nom doit contenir au moins 3 caractères';
                            this.valid.name = false;
                        } else if (this.form.name.length > 255) {
                            this.errors.name = 'Le nom ne peut pas dépasser 255 caractères';
                            this.valid.name = false;
                        } else {
                            this.errors.name = '';
                            this.valid.name = true;
                        }
                        break;
                        
                    case 'category':
                        if (!this.form.category) {
                            this.errors.category = 'Veuillez sélectionner une catégorie';
                            this.valid.category = false;
                        } else {
                            this.errors.category = '';
                            this.valid.category = true;
                        }
                        break;
                        
                    case 'description':
                        if (!this.form.description.trim()) {
                            this.errors.description = 'La description est requise';
                            this.valid.description = false;
                        } else if (this.form.description.length < 20) {
                            this.errors.description = 'La description doit contenir au moins 20 caractères';
                            this.valid.description = false;
                        } else {
                            this.errors.description = '';
                            this.valid.description = true;
                        }
                        break;
                        
                    case 'price':
                        if (!this.form.price) {
                            this.errors.price = 'Le prix est requis';
                            this.valid.price = false;
                        } else if (parseFloat(this.form.price) <= 0) {
                            this.errors.price = 'Le prix doit être supérieur à 0';
                            this.valid.price = false;
                        } else {
                            this.errors.price = '';
                            this.valid.price = true;
                        }
                        break;
                        
                    case 'stock':
                        if (this.form.stock === '' || this.form.stock === null) {
                            this.errors.stock = 'Le stock est requis';
                            this.valid.stock = false;
                        } else if (parseInt(this.form.stock) < 0) {
                            this.errors.stock = 'Le stock ne peut pas être négatif';
                            this.valid.stock = false;
                        } else {
                            this.errors.stock = '';
                            this.valid.stock = true;
                        }
                        break;
                }
            },
            
            // Validation globale
            validateAll() {
                this.validateField('name');
                this.validateField('category');
                this.validateField('description');
                this.validateField('price');
                this.validateField('stock');
                this.validateImages();
            },
            
            // Validation des images
            validateImages() {
                if (this.images.length === 0) {
                    this.errors.images = 'Ajoutez au moins une image du produit';
                } else {
                    this.errors.images = '';
                }
            },
            
            // Propriété calculée pour la validité du formulaire
            get isValid() {
                return this.valid.name && 
                       this.valid.category && 
                       this.valid.description && 
                       this.valid.price && 
                       this.valid.stock && 
                       this.images.length > 0;
            },
            
            // Gestion des fichiers
            handleFileSelect(event) {
                this.handleFiles(event.target.files);
            },
            
            handleDrop(event) {
                this.dragover = false;
                this.handleFiles(event.dataTransfer.files);
            },
            
            handleFiles(files) {
                const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
                const maxSize = 5 * 1024 * 1024; // 5MB
                
                for (let file of files) {
                    // Vérifier le type
                    if (!validTypes.includes(file.type)) {
                        this.showNotification('Format non supporté: ' + file.name, 'error');
                        continue;
                    }
                    
                    // Vérifier la taille
                    if (file.size > maxSize) {
                        this.showNotification('Fichier trop volumineux: ' + file.name, 'error');
                        continue;
                    }
                    
                    // Limite de 10 images
                    if (this.images.length >= 10) {
                        this.showNotification('Maximum 10 images', 'warning');
                        break;
                    }
                    
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        this.images.push({
                            file: file,
                            preview: e.target.result,
                            error: null
                        });
                        this.validateImages();
                    };
                    reader.readAsDataURL(file);
                }
            },
            
            removeImage(index) {
                this.images.splice(index, 1);
                this.validateImages();
            },
            
            // Gestion des attributs
            addAttribute() {
                this.attributes.push({ name: '', value: '' });
            },
            
            removeAttribute(index) {
                this.attributes.splice(index, 1);
            },
            
            // Validation du poids
            validateWeight() {
                if (this.form.weight && parseFloat(this.form.weight) <= 0) {
                    return 'Le poids doit être supérieur à 0';
                }
                return null;
            },
            
            // Validation des dimensions
            validateDimensions() {
                if (this.form.dimensions) {
                    const pattern = /^\d+\s*x\s*\d+\s*x\s*\d+$/i;
                    if (!pattern.test(this.form.dimensions)) {
                        return 'Format invalide. Utilisez: L x l x h (ex: 30 x 20 x 10)';
                    }
                }
                return null;
            },
            
            // Soumission du formulaire
            async submitProduct() {
                this.validateAll();
                
                if (!this.isValid) {
                    this.showNotification('Veuillez corriger les erreurs du formulaire', 'error');
                    this.errors.global = 'Veuillez remplir tous les champs obligatoires';
                    setTimeout(() => { this.errors.global = ''; }, 5000);
                    return;
                }
                
                this.isSubmitting = true;
                this.errors.global = '';
                
                const formData = new FormData();
                
                // Ajouter les champs texte
                formData.append('name', this.form.name);
                formData.append('category', this.form.category);
                formData.append('description', this.form.description);
                formData.append('price', this.form.price);
                if (this.form.compareAtPrice) formData.append('compareAtPrice', this.form.compareAtPrice);
                formData.append('stock', this.form.stock);
                if (this.form.weight) formData.append('weight', this.form.weight);
                if (this.form.dimensions) formData.append('dimensions', this.form.dimensions);
                
                // Ajouter les images
                for (let image of this.images) {
                    formData.append('images[]', image.file);
                }
                
                // Ajouter les attributs
                const validAttributes = this.attributes.filter(attr => attr.name && attr.value);
                if (validAttributes.length > 0) {
                    formData.append('attributes', JSON.stringify(validAttributes));
                }
                
                try {
                    const response = await fetch('/api/vendor/products', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const data = await response.json();
                    
                    if (response.ok) {
                        this.showNotification('Produit créé avec succès !', 'success');
                        setTimeout(() => {
                            window.location.href = '{{ path('vendor_products') }}';
                        }, 1500);
                    } else {
                        this.errors.global = data.error || data.message || 'Erreur lors de la création';
                        this.showNotification(this.errors.global, 'error');
                    }
                } catch (error) {
                    console.error('Error:', error);
                    this.errors.global = 'Erreur de connexion au serveur';
                    this.showNotification(this.errors.global, 'error');
                } finally {
                    this.isSubmitting = false;
                }
            },
            
            showNotification(message, type = 'success') {
                if (window.showNotification) {
                    window.showNotification(message, type);
                } else {
                    alert(message);
                }
            }
        }
    }
</script>

<style>
    [x-cloak] { display: none !important; }
    
    input:focus, textarea:focus, select:focus {
        outline: none;
        ring: 2px solid #3b82f6;
    }
    
    input.border-red-500:focus, textarea.border-red-500:focus, select.border-red-500:focus {
        border-color: #ef4444;
        ring-color: #ef4444;
    }
    
    input.border-green-500:focus, textarea.border-green-500:focus, select.border-green-500:focus {
        border-color: #10b981;
        ring-color: #10b981;
    }
</style>
{% endblock %}