'use client'; import { useEffect, useState } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; type ItemType = 'task' | 'project' | 'habit'; const labels = { task: { title: 'New task', field: 'Task title' }, project: { title: 'New project', field: 'Project name' }, habit: { title: 'New habit', field: 'Habit name' }, } as const; interface Domain { id: string; name: string; color: string; } export function CreateItemDialog({ type, open, onOpenChange, onCreated, }: { type: ItemType; open: boolean; onOpenChange: (open: boolean) => void; onCreated: () => void; }) { const [name, setName] = useState(''); const [domain, setDomain] = useState(''); const [domains, setDomains] = useState([]); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(''); const copy = labels[type]; useEffect(() => { if (open) { fetch('/api/domains?sort=sort_order') .then((res) => res.json()) .then((data) => { const items = data.items || []; setDomains(items); if (items.length > 0 && !domain) { setDomain(items[0].id); } }) .catch(() => { setDomains([]); }); } }, [open]); // eslint-disable-line react-hooks/exhaustive-deps async function handleSubmit(event: React.FormEvent) { event.preventDefault(); setSubmitting(true); setError(''); const body = type === 'task' ? { title: name, domain, status: 'todo', priority: 'medium', tags: [] } : type === 'project' ? { name, domain, status: 'active', tags: [] } : { name, domain, frequency: 'daily', difficulty: 'medium', completion_mode: 'quick', goal_per_period: 1, active: true, tags: [], }; try { const response = await fetch(`/api/${type === 'task' ? 'tasks' : `${type}s`}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); if (!response.ok) { throw new Error('Unable to create item'); } setName(''); onOpenChange(false); onCreated(); } catch { setError(`Unable to create this ${type}. Please try again.`); } finally { setSubmitting(false); } } return ( {copy.title} Give it a name and choose where it belongs.
setName(event.target.value)} autoFocus required />
{domains.length > 0 ? ( ) : (

No domains found. Create one in Settings first.

)}
{error &&

{error}

}
); }