'use client' import { useState, useEffect } from 'react' import { useRouter } from 'next/navigation' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Textarea } from '@/components/ui/textarea' import { Switch } from '@/components/ui/switch' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select' import { ArrowLeft, Save, Upload, X, ImageIcon } from 'lucide-react' import { toast } from 'sonner' import Link from 'next/link' import Image from 'next/image' import MediaSelector, { MediaFile } from '@/components/admin/MediaSelector' interface Product { id?: string name: string description: string price: number discount: number images: string[] stock: number manageStock: boolean sku: string isActive: boolean categoryId: string } interface Category { id: string name: string } interface ProductFormProps { product?: Product } export function ProductForm({ product }: ProductFormProps) { const router = useRouter() const [loading, setLoading] = useState(false) const [categoriesLoading, setCategoriesLoading] = useState(true) const [categories, setCategories] = useState([]) const [imageUrl, setImageUrl] = useState('') const [formData, setFormData] = useState({ name: '', description: '', price: 0, discount: 0, images: [], stock: 0, manageStock: true, sku: '', isActive: true, categoryId: '', ...product }) useEffect(() => { fetchCategories() }, []) const fetchCategories = async () => { try { setCategoriesLoading(true) const response = await fetch('/api/categories') const data = await response.json() // Handle the new API response structure setCategories(data.categories || []) } catch (error) { console.error('Error fetching categories:', error) setCategories([]) // Fallback to empty array } finally { setCategoriesLoading(false) } } const handleInputChange = (field: keyof Product, value: any) => { setFormData(prev => ({ ...prev, [field]: value })) } const handleAddImageUrl = () => { if (!imageUrl.trim()) { toast.error('Please enter a valid image URL') return } // Basic URL validation try { new URL(imageUrl) } catch { toast.error('Please enter a valid URL') return } setFormData(prev => ({ ...prev, images: [...prev.images, imageUrl.trim()] })) setImageUrl('') toast.success('Image URL added') } const removeImage = (index: number) => { setFormData(prev => ({ ...prev, images: prev.images.filter((_, i) => i !== index) })) } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setLoading(true) try { const url = product ? `/api/admin/products/${product.id}` : '/api/admin/products' const method = product ? 'PUT' : 'POST' const response = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) }) if (!response.ok) throw new Error('Failed to save product') toast.success(`Product ${product ? 'updated' : 'created'} successfully`) router.push('/admin/products') } catch (error) { toast.error(`Failed to ${product ? 'update' : 'create'} product`) } finally { setLoading(false) } } return (
Product Information
handleInputChange('name', e.target.value)} required />