'use client'; import { useState, useEffect } from 'react'; import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/components/ui/dialog'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Textarea } from '@/components/ui/textarea'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; import { Switch } from '@/components/ui/switch'; import { toast } from 'sonner'; interface HabitCreateDialogProps { open: boolean; onOpenChange: (open: boolean) => void; domainId: string; onCreated: () => void; } export function HabitCreateDialog({ open, onOpenChange, domainId, onCreated, }: HabitCreateDialogProps) { const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [frequency, setFrequency] = useState<'daily' | 'weekly' | 'custom'>('daily'); const [difficulty, setDifficulty] = useState<'easy' | 'medium' | 'hard'>('medium'); const [goalPerPeriod, setGoalPerPeriod] = useState('1'); const [unit, setUnit] = useState(''); const [reminderTime, setReminderTime] = useState(''); const [moodTracking, setMoodTracking] = useState(false); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(''); useEffect(() => { if (open) { setName(''); setDescription(''); setFrequency('daily'); setDifficulty('medium'); setGoalPerPeriod('1'); setUnit(''); setReminderTime(''); setMoodTracking(false); setError(''); } }, [open]); async function handleSubmit(event: React.FormEvent) { event.preventDefault(); if (!domainId) { setError('No domain selected'); return; } setSubmitting(true); setError(''); const body: Record = { name, frequency, difficulty, goalPerPeriod: parseInt(goalPerPeriod, 10) || 1, moodTracking, }; if (description) body.description = description; if (unit) body.unit = unit; if (reminderTime) body.reminderTime = reminderTime; try { const response = await fetch(`/api/domains/${domainId}/habits`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); if (!response.ok) { const err = await response.json(); throw new Error(err.error?.message || 'Unable to create habit'); } toast.success('Habit created'); onOpenChange(false); onCreated(); } catch (err) { setError(err instanceof Error ? err.message : 'Unable to create habit'); } finally { setSubmitting(false); } } return ( New Habit Create a new habit to track daily or weekly.
setName(e.target.value)} placeholder="e.g. Morning meditation" autoFocus required />