import { useState, FormEvent } from 'react'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { toast } from 'sonner'; import api, { getErrorMessage } from '@/lib/api'; import type { Location } from '@/types'; import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter, SheetClose, } from '@/components/ui/sheet'; import { Input } from '@/components/ui/input'; import { Textarea } from '@/components/ui/textarea'; import { Select } from '@/components/ui/select'; import { Label } from '@/components/ui/label'; import { Button } from '@/components/ui/button'; import LocationPicker from '@/components/ui/location-picker'; interface LocationFormProps { location: Location | null; onClose: () => void; } export default function LocationForm({ location, onClose }: LocationFormProps) { const queryClient = useQueryClient(); const [formData, setFormData] = useState({ name: location?.name || '', address: location?.address || '', category: location?.category || 'other', notes: location?.notes || '', }); const mutation = useMutation({ mutationFn: async (data: typeof formData) => { if (location) { const response = await api.put(`/locations/${location.id}`, data); return response.data; } else { const response = await api.post('/locations', data); return response.data; } }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['locations'] }); toast.success(location ? 'Location updated' : 'Location created'); onClose(); }, onError: (error) => { toast.error(getErrorMessage(error, location ? 'Failed to update location' : 'Failed to create location')); }, }); const handleSubmit = (e: FormEvent) => { e.preventDefault(); mutation.mutate(formData); }; return ( {location ? 'Edit Location' : 'New Location'}
setFormData({ ...formData, name: e.target.value })} required />
setFormData({ ...formData, address: val })} onSelect={(result) => { setFormData({ ...formData, name: formData.name || result.name, address: result.address, }); }} placeholder="Search or type an address..." />