import { useEffect, useState } from "react"; import { useNavigate } from "@tanstack/react-router"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; 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 { toast } from "sonner"; import { trpc } from "@/lib/trpc"; import { ProjectPicker } from "./ProjectPicker"; interface CreateInitiativeDialogProps { open: boolean; onOpenChange: (open: boolean) => void; } export function CreateInitiativeDialog({ open, onOpenChange, }: CreateInitiativeDialogProps) { const [name, setName] = useState(""); const [description, setDescription] = useState(""); const [branch, setBranch] = useState(""); const [projectIds, setProjectIds] = useState([]); const [executionMode, setExecutionMode] = useState<"yolo" | "review_per_phase">("review_per_phase"); const [error, setError] = useState(null); const navigate = useNavigate(); const utils = trpc.useUtils(); const createMutation = trpc.createInitiative.useMutation({ onMutate: async ({ name }) => { await utils.listInitiatives.cancel(); const previousInitiatives = utils.listInitiatives.getData(); const tempInitiative = { id: `temp-${Date.now()}`, name: name.trim(), createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), branch: null, projects: [], activity: { state: 'idle' as const, phasesTotal: 0, phasesCompleted: 0 }, }; utils.listInitiatives.setData(undefined, (old = []) => [tempInitiative, ...old]); return { previousInitiatives }; }, onSuccess: (data) => { onOpenChange(false); toast.success("Initiative created"); navigate({ to: "/initiatives/$id", params: { id: data.id } }); }, onError: (err, _variables, context) => { if (context?.previousInitiatives) { utils.listInitiatives.setData(undefined, context.previousInitiatives); } setError(err.message); toast.error("Failed to create initiative"); }, }); // Reset form when dialog opens useEffect(() => { if (open) { setName(""); setDescription(""); setBranch(""); setProjectIds([]); setExecutionMode("review_per_phase"); setError(null); } }, [open]); function handleSubmit(e: React.FormEvent) { e.preventDefault(); setError(null); createMutation.mutate({ name: name.trim(), description: description.trim() || undefined, branch: branch.trim() || null, projectIds: projectIds.length > 0 ? projectIds : undefined, executionMode, }); } const canSubmit = name.trim().length > 0 && !createMutation.isPending; return ( Create Initiative Create a new initiative to plan and execute work.
setName(e.target.value)} autoFocus />