import { useState, useEffect } from 'react' import { useNavigate, useParams } from 'react-router-dom' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api } from '../api/client' export default function ProjectFormPage() { const { id } = useParams<{ id: string }>() const navigate = useNavigate() const queryClient = useQueryClient() const isEditing = !!id const [name, setName] = useState('') const [slug, setSlug] = useState('') const [description, setDescription] = useState('') const [errors, setErrors] = useState>({}) const { data: project } = useQuery({ queryKey: ['project', id], queryFn: () => api.getProject(id!), enabled: isEditing, }) useEffect(() => { if (project) { setName(project.name) setSlug(project.slug) setDescription(project.description || '') } }, [project]) const createMutation = useMutation({ mutationFn: api.createProject, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['projects'] }) navigate('/projects') }, }) const updateMutation = useMutation({ mutationFn: ({ id, data }: { id: string; data: Parameters[1] }) => api.updateProject(id, data), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['projects'] }) queryClient.invalidateQueries({ queryKey: ['project', id] }) navigate(`/projects/${id}`) }, }) const validate = () => { const newErrors: Record = {} if (!name.trim()) newErrors.name = 'Name is required' if (!slug.trim()) newErrors.slug = 'Slug is required' if (!/^[a-z0-9-]+$/i.test(slug)) newErrors.slug = 'Slug must contain only letters, numbers, and hyphens' setErrors(newErrors) return Object.keys(newErrors).length === 0 } const handleSubmit = (e: React.FormEvent) => { e.preventDefault() if (!validate()) return const data = { name: name.trim(), slug: slug.trim(), description: description.trim() || null, } if (isEditing) { updateMutation.mutate({ id: id!, data }) } else { createMutation.mutate(data) } } return (

{isEditing ? 'Edit Project' : 'New Project'}

setName(e.target.value)} className="w-full px-3 py-2 rounded-lg border border-border bg-surface" placeholder="My Awesome Project" /> {errors.name &&

{errors.name}

}
setSlug(e.target.value)} className="w-full px-3 py-2 rounded-lg border border-border bg-surface" placeholder="my-awesome-project" /> {errors.slug &&

{errors.slug}

}