import { useEffect, useState } from "react"; import type { BudgetPolicyRecord } from "@shared/types"; import { ActionButton, Input, Modal, Select } from "../ui"; import { buildBudgetPolicyInput, getBudgetPolicyAmountDollars } from "../../lib/budget-policy-input"; interface PolicyFormModalProps { open: boolean; onClose: () => void; onSaved: () => void; companyId: string; editingPolicy: BudgetPolicyRecord | null; agents: Array<{ id: string; name: string }>; projects: Array<{ id: string; name: string }>; } export function PolicyFormModal({ open, onClose, onSaved, companyId, editingPolicy, agents, projects }: PolicyFormModalProps) { const [scopeType, setScopeType] = useState<"company" | "agent" | "project">("company"); const [scopeId, setScopeId] = useState(companyId); const [amountDollars, setAmountDollars] = useState("100"); const [warnPercent, setWarnPercent] = useState("80"); const [hardStopEnabled, setHardStopEnabled] = useState(true); const [notifyEnabled, setNotifyEnabled] = useState(true); const [saving, setSaving] = useState(false); useEffect(() => { if (editingPolicy) { setScopeType(editingPolicy.scopeType); setScopeId(editingPolicy.scopeId); setAmountDollars(getBudgetPolicyAmountDollars(editingPolicy)); setWarnPercent(String(editingPolicy.warnPercent)); setHardStopEnabled(editingPolicy.hardStopEnabled); setNotifyEnabled(editingPolicy.notifyEnabled); } else { setScopeType("company"); setScopeId(companyId); setAmountDollars("100"); setWarnPercent("80"); setHardStopEnabled(true); setNotifyEnabled(true); } }, [editingPolicy, companyId]); useEffect(() => { if (scopeType === "company") { setScopeId(companyId); } else if (scopeType === "agent" && agents.length > 0) { setScopeId(agents[0].id); } else if (scopeType === "project" && projects.length > 0) { setScopeId(projects[0].id); } }, [scopeType, companyId, agents, projects]); async function handleSave() { setSaving(true); try { const payload = buildBudgetPolicyInput({ policyId: editingPolicy?.id ?? null, companyId, scopeType, scopeId, amountDollars, warnPercent, hardStopEnabled, notifyEnabled, }); if (!payload) return; const result = await window.agentCompany.saveBudgetPolicy(payload); if (result.ok) { onSaved(); onClose(); } } finally { setSaving(false); } } return (
({ value: a.id, label: a.name }))} /> ) : null} {scopeType === "project" ? (
void handleSave()} />
); }