import { useState, FormEvent } from 'react'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { toast } from 'sonner'; import api, { getErrorMessage } from '@/lib/api'; import type { EventTemplate, Location } from '@/types'; import { useCalendars } from '@/hooks/useCalendars'; 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 { Checkbox } from '@/components/ui/checkbox'; import LocationPicker from '@/components/ui/location-picker'; interface TemplateFormProps { template: EventTemplate | null; onClose: () => void; } export default function TemplateForm({ template, onClose }: TemplateFormProps) { const queryClient = useQueryClient(); const { data: calendars = [] } = useCalendars(); const selectableCalendars = calendars.filter((c) => !c.is_system); const { data: locations = [] } = useQuery({ queryKey: ['locations'], queryFn: async () => { const { data } = await api.get('/locations'); return data; }, }); const existingLocation = locations.find((l) => l.id === template?.location_id); const [locationSearch, setLocationSearch] = useState(existingLocation?.name || ''); const [formData, setFormData] = useState({ name: template?.name || '', title: template?.title || '', description: template?.description || '', calendar_id: template?.calendar_id?.toString() || '', location_id: template?.location_id?.toString() || '', all_day: template?.all_day || false, is_starred: template?.is_starred || false, }); const mutation = useMutation({ mutationFn: async (data: typeof formData) => { const payload = { name: data.name, title: data.title, description: data.description || null, calendar_id: data.calendar_id ? parseInt(data.calendar_id) : null, location_id: data.location_id ? parseInt(data.location_id) : null, all_day: data.all_day, is_starred: data.is_starred, }; if (template) { const { data: res } = await api.put(`/event-templates/${template.id}`, payload); return res; } else { const { data: res } = await api.post('/event-templates', payload); return res; } }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['event-templates'] }); toast.success(template ? 'Template updated' : 'Template created'); onClose(); }, onError: (error) => { toast.error(getErrorMessage(error, 'Failed to save template')); }, }); const handleSubmit = (e: FormEvent) => { e.preventDefault(); if (!formData.name.trim() || !formData.title.trim()) return; mutation.mutate(formData); }; return ( {template ? 'Edit Template' : 'New Template'}
setFormData({ ...formData, name: e.target.value })} placeholder="e.g., Weekly standup" required />
setFormData({ ...formData, title: e.target.value })} placeholder="Title for created events" required />