import { useEffect, useState } from "react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { apiRequest } from "@/lib/queryClient"; import { toast } from "@/hooks/use-toast"; type CredentialFormProps = { onClose: () => void; userId: number; defaultValues?: { id?: number; siteKey: string; username: string; password: string; }; }; // Available site keys - must match exactly what the automation buttons expect const SITE_KEY_OPTIONS = [ { value: "MH", label: "MassHealth" }, { value: "DDMA", label: "Delta Dental MA" }, { value: "DELTAINS", label: "Delta Dental Ins" }, { value: "DENTAQUEST", label: "Tufts SCO / DentaQuest" }, { value: "UNITEDSCO", label: "United SCO" }, ]; export function CredentialForm({ onClose, userId, defaultValues }: CredentialFormProps) { const [siteKey, setSiteKey] = useState(defaultValues?.siteKey || ""); const [username, setUsername] = useState(defaultValues?.username || ""); const [password, setPassword] = useState(defaultValues?.password || ""); const queryClient = useQueryClient(); // Create or Update Mutation inside form const mutation = useMutation({ mutationFn: async () => { const payload = { siteKey: siteKey.trim(), username: username.trim(), password: password.trim(), userId, }; const url = defaultValues?.id ? `/api/insuranceCreds/${defaultValues.id}` : "/api/insuranceCreds/"; const method = defaultValues?.id ? "PUT" : "POST"; const res = await apiRequest(method, url, payload); if (!res.ok) { const errorData = await res.json().catch(() => null); throw new Error(errorData?.message || "Failed to save credential"); } return res.json(); }, onSuccess: () => { toast({ title: `Credential ${defaultValues?.id ? "updated" : "created"}.`, }); queryClient.invalidateQueries({ queryKey: ["/api/insuranceCreds/"] }); onClose(); }, onError: (error: any) => { toast({ title: "Error", description: error.message || "Unknown error", variant: "destructive", }); }, }); // Reset form on defaultValues change (edit mode) useEffect(() => { setSiteKey(defaultValues?.siteKey || ""); setUsername(defaultValues?.username || ""); setPassword(defaultValues?.password || ""); }, [defaultValues]); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!siteKey || !username || !password) { toast({ title: "Error", description: "All fields are required.", variant: "destructive", }); return; } mutation.mutate(); }; return (