340 lines
11 KiB
TypeScript
340 lines
11 KiB
TypeScript
// ============================================
|
|
// components/admin/ProductCreateModal.tsx - VERSION AVEC BOUTONS
|
|
// ============================================
|
|
// ✅ Boutons stylisés au lieu de select natif (comme AdminUsers)
|
|
// ✅ Pas de hover gris natif !
|
|
|
|
import React, { useState } from 'react';
|
|
import { X, Plus, Trash2, Upload, DollarSign } from 'lucide-react';
|
|
import { createProductAdmin } from '../api/api_admin';
|
|
import type { CreateProductData, ProductPrice} from '../api/api_admin_types';
|
|
import './ProductModal.css';
|
|
|
|
interface ProductCreateModalProps {
|
|
onClose: () => void;
|
|
onSuccess: () => void;
|
|
}
|
|
|
|
const ProductCreateModal: React.FC<ProductCreateModalProps> = ({ onClose, onSuccess }) => {
|
|
// ============================================
|
|
// 📝 STATE
|
|
// ============================================
|
|
const [name, setName] = useState('');
|
|
const [category, setCategory] = useState('weed&hash');
|
|
const [description, setDescription] = useState('');
|
|
const [stock, setStock] = useState<number>(0);
|
|
const [prices, setPrices] = useState<ProductPrice[]>([
|
|
{ quantity: 1, price: 0 }
|
|
]);
|
|
const [mediaFiles, setMediaFiles] = useState<File[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
// ✅ Options de catégories
|
|
const categoryOptions = [
|
|
{ value: 'weed&hash', label: 'Weed & Hash' },
|
|
{ value: 'zipette&co', label: 'Zipette & Co' },
|
|
{ value: 'gros&semi', label: 'Gros & Semi' }
|
|
];
|
|
|
|
// ============================================
|
|
// 💰 GESTION DES PRIX
|
|
// ============================================
|
|
const addPriceRow = () => {
|
|
setPrices([...prices, { quantity: 1, price: 0 }]);
|
|
};
|
|
|
|
const removePriceRow = (index: number) => {
|
|
if (prices.length > 1) {
|
|
setPrices(prices.filter((_, i) => i !== index));
|
|
}
|
|
};
|
|
|
|
const updatePrice = (index: number, field: 'quantity' | 'price', value: number) => {
|
|
const newPrices = [...prices];
|
|
newPrices[index][field] = value;
|
|
setPrices(newPrices);
|
|
};
|
|
|
|
// ============================================
|
|
// 📁 GESTION DES FICHIERS
|
|
// ============================================
|
|
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
if (e.target.files) {
|
|
const newFiles = Array.from(e.target.files);
|
|
setMediaFiles([...mediaFiles, ...newFiles]);
|
|
console.log(`📁 ${newFiles.length} fichier(s) ajouté(s)`);
|
|
}
|
|
};
|
|
|
|
const removeFile = (index: number) => {
|
|
setMediaFiles(mediaFiles.filter((_, i) => i !== index));
|
|
};
|
|
|
|
// ============================================
|
|
// ✅ VALIDATION
|
|
// ============================================
|
|
const validateForm = (): string | null => {
|
|
if (!name.trim()) return 'Le nom est requis';
|
|
if (!description.trim()) return 'La description est requise';
|
|
if (stock < 0) return 'Le stock ne peut pas être négatif';
|
|
if (prices.length === 0) return 'Au moins un prix est requis';
|
|
|
|
for (const price of prices) {
|
|
if (price.quantity <= 0) return 'Toutes les quantités doivent être positives';
|
|
if (price.price <= 0) return 'Tous les prix doivent être positifs';
|
|
}
|
|
|
|
return null;
|
|
};
|
|
|
|
// ============================================
|
|
// 📤 SOUMISSION
|
|
// ============================================
|
|
const handleSubmit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
|
|
const validationError = validateForm();
|
|
if (validationError) {
|
|
setError(validationError);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
console.log('📤 [CREATE_MODAL] Envoi du formulaire...');
|
|
|
|
const productData: CreateProductData = {
|
|
name: name.trim(),
|
|
category,
|
|
description: description.trim(),
|
|
stock,
|
|
prices,
|
|
};
|
|
|
|
const response = await createProductAdmin(productData, mediaFiles);
|
|
|
|
if (response.success) {
|
|
console.log('✅ [CREATE_MODAL] Produit créé avec succès');
|
|
onSuccess();
|
|
} else {
|
|
setError(response.error || 'Erreur lors de la création du produit');
|
|
}
|
|
} catch (error) {
|
|
console.error('❌ [CREATE_MODAL] Erreur:', error);
|
|
setError(error instanceof Error ? error.message : 'Erreur inconnue');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
// ============================================
|
|
// 🎨 RENDER
|
|
// ============================================
|
|
return (
|
|
<>
|
|
<div className="modal-overlay" onClick={onClose} />
|
|
<div className="product-modal">
|
|
{/* Header */}
|
|
<div className="modal-header">
|
|
<h2>Créer un Nouveau Produit</h2>
|
|
<button className="close-modal" onClick={onClose}>
|
|
<X size={24} />
|
|
</button>
|
|
</div>
|
|
|
|
{/* Content */}
|
|
<form onSubmit={handleSubmit} className="modal-content">
|
|
{error && (
|
|
<div className="error-message">
|
|
<p>{error}</p>
|
|
</div>
|
|
)}
|
|
|
|
{/* Informations de base */}
|
|
<div className="form-section">
|
|
<h3>Informations de Base</h3>
|
|
|
|
<div className="form-group">
|
|
<label htmlFor="name">Nom du Produit *</label>
|
|
<input
|
|
id="name"
|
|
type="text"
|
|
value={name}
|
|
onChange={(e) => setName(e.target.value)}
|
|
placeholder="Ex: OG Kush Premium"
|
|
required
|
|
/>
|
|
</div>
|
|
|
|
{/* ✅ CATÉGORIE AVEC BOUTONS AU LIEU DE SELECT */}
|
|
<div className="form-group">
|
|
<label>Catégorie *</label>
|
|
<div className="filter-buttons">
|
|
{categoryOptions.map(option => (
|
|
<button
|
|
key={option.value}
|
|
type="button"
|
|
className={category === option.value ? 'active' : ''}
|
|
onClick={() => setCategory(option.value)}
|
|
disabled={loading}
|
|
>
|
|
{option.label}
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="form-group">
|
|
<label htmlFor="description">Description *</label>
|
|
<textarea
|
|
id="description"
|
|
value={description}
|
|
onChange={(e) => setDescription(e.target.value)}
|
|
placeholder="Décrivez le produit en détail..."
|
|
rows={4}
|
|
required
|
|
/>
|
|
</div>
|
|
|
|
<div className="form-group">
|
|
<label htmlFor="stock">Stock (en grammes) *</label>
|
|
<input
|
|
id="stock"
|
|
type="number"
|
|
min="0"
|
|
step="0.1"
|
|
value={stock}
|
|
onChange={(e) => setStock(parseFloat(e.target.value))}
|
|
placeholder="100"
|
|
required
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Prix */}
|
|
<div className="form-section">
|
|
<div className="section-header">
|
|
<h3>Tarifs</h3>
|
|
<button type="button" className="add-price-btn" onClick={addPriceRow}>
|
|
<Plus size={18} />
|
|
Ajouter un Prix
|
|
</button>
|
|
</div>
|
|
|
|
<div className="prices-grid">
|
|
{prices.map((price, index) => (
|
|
<div key={index} className="price-row">
|
|
<div className="price-input-group">
|
|
<label>Quantité (g)</label>
|
|
<input
|
|
type="number"
|
|
min="1"
|
|
step="1"
|
|
value={price.quantity}
|
|
onChange={(e) => updatePrice(index, 'quantity', parseInt(e.target.value))}
|
|
required
|
|
/>
|
|
</div>
|
|
|
|
<div className="price-input-group">
|
|
<label>Prix (€)</label>
|
|
<div className="price-input-wrapper">
|
|
<DollarSign size={18} />
|
|
<input
|
|
type="number"
|
|
min="0"
|
|
step="0.01"
|
|
value={price.price}
|
|
onChange={(e) => updatePrice(index, 'price', parseFloat(e.target.value))}
|
|
required
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{prices.length > 1 && (
|
|
<button
|
|
type="button"
|
|
className="remove-price-btn"
|
|
onClick={() => removePriceRow(index)}
|
|
title="Supprimer ce prix"
|
|
>
|
|
<Trash2 size={18} />
|
|
</button>
|
|
)}
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Médias */}
|
|
<div className="form-section">
|
|
<h3>Médias (Images & Vidéos)</h3>
|
|
|
|
<div className="upload-zone">
|
|
<label htmlFor="media-upload" className="upload-label">
|
|
<Upload size={32} />
|
|
<p>Cliquez pour ajouter des fichiers</p>
|
|
<span>Images (JPG, PNG, WebP) ou Vidéos (MP4, WebM)</span>
|
|
</label>
|
|
<input
|
|
id="media-upload"
|
|
type="file"
|
|
accept="image/*,video/*"
|
|
multiple
|
|
onChange={handleFileSelect}
|
|
style={{ display: 'none' }}
|
|
/>
|
|
</div>
|
|
|
|
{mediaFiles.length > 0 && (
|
|
<div className="files-list">
|
|
{mediaFiles.map((file, index) => (
|
|
<div key={index} className="file-item">
|
|
<div className="file-info">
|
|
<span className="file-name">{file.name}</span>
|
|
<span className="file-size">
|
|
{(file.size / 1024).toFixed(1)} KB
|
|
</span>
|
|
</div>
|
|
<button
|
|
type="button"
|
|
className="remove-file-btn"
|
|
onClick={() => removeFile(index)}
|
|
>
|
|
<Trash2 size={16} />
|
|
</button>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</form>
|
|
|
|
{/* Footer */}
|
|
<div className="modal-actions">
|
|
<button
|
|
type="button"
|
|
className="action-button secondary"
|
|
onClick={onClose}
|
|
disabled={loading}
|
|
>
|
|
Annuler
|
|
</button>
|
|
<button
|
|
type="submit"
|
|
className="action-button primary"
|
|
onClick={handleSubmit}
|
|
disabled={loading}
|
|
>
|
|
{loading ? 'Création...' : 'Créer le Produit'}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</>
|
|
);
|
|
};
|
|
|
|
export default ProductCreateModal; |