'use client' import { useState } from 'react' import { useRouter } from 'next/navigation' import { updateItem, createItem } from '@/lib/actions' interface ItemFormProps { listId: string item?: { id: string title: string description: string | null priority: string dueDate: Date | null tags: any notes: string | null } mode?: 'create' | 'edit' } export default function ItemForm({ listId, item, mode = 'edit' }: ItemFormProps) { const router = useRouter() const [isSubmitting, setIsSubmitting] = useState(false) const [errors, setErrors] = useState>({}) // Form state const [title, setTitle] = useState(item?.title || '') const [description, setDescription] = useState(item?.description || '') const [priority, setPriority] = useState<'low' | 'medium' | 'high'>( (item?.priority as 'low' | 'medium' | 'high') || 'medium' ) const [dueDate, setDueDate] = useState( item?.dueDate ? new Date(item.dueDate).toISOString().split('T')[0] : '' ) const [tags, setTags] = useState( Array.isArray(item?.tags) ? item.tags : [] ) const [tagInput, setTagInput] = useState('') const [notes, setNotes] = useState(item?.notes || '') const validateForm = () => { const newErrors: Record = {} if (!title.trim()) { newErrors.title = 'Title is required' } if (title.length > 200) { newErrors.title = 'Title must be less than 200 characters' } setErrors(newErrors) return Object.keys(newErrors).length === 0 } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() if (!validateForm()) { return } setIsSubmitting(true) try { const data = { title: title.trim(), description: description.trim() || null, priority, dueDate: dueDate ? new Date(dueDate) : null, tags, notes: notes.trim() || null, } if (mode === 'create') { await createItem(listId, data.title, data.description || undefined, { priority: data.priority, dueDate: data.dueDate, tags: data.tags, notes: data.notes, }) router.push(`/list/${listId}`) } else if (item) { await updateItem(item.id, data) router.push(`/list/${listId}/item/${item.id}`) } } catch (error) { console.error('Error saving item:', error) setErrors({ submit: 'Failed to save item. Please try again.' }) } finally { setIsSubmitting(false) } } const handleAddTag = () => { const tag = tagInput.trim() if (tag && !tags.includes(tag)) { setTags([...tags, tag]) setTagInput('') } } const handleRemoveTag = (tagToRemove: string) => { setTags(tags.filter((tag) => tag !== tagToRemove)) } const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { e.preventDefault() handleAddTag() } } return (
{/* Title */}
setTitle(e.target.value)} className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${ errors.title ? 'border-red-500' : 'border-gray-300' }`} placeholder="Enter task title" /> {errors.title && (

{errors.title}

)}
{/* Description */}