"use client"; import { useQuery } from "@tanstack/react-query"; import { useAtomValue } from "jotai"; import { AlertTriangle, Info } from "lucide-react"; import { useEffect, useState } from "react"; import { toast } from "sonner"; import { updateWorkspaceMutationAtom } from "@/atoms/workspaces/workspace-mutation.atoms"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Skeleton } from "@/components/ui/skeleton"; import { Textarea } from "@/components/ui/textarea"; import { workspacesApiService } from "@/lib/apis/workspaces-api.service"; import { cacheKeys } from "@/lib/query-client/cache-keys"; import { Spinner } from "../ui/spinner"; interface PromptConfigManagerProps { workspaceId: number; } export function PromptConfigManager({ workspaceId }: PromptConfigManagerProps) { const { data: workspace, isLoading: loading } = useQuery({ queryKey: cacheKeys.workspaces.detail(workspaceId.toString()), queryFn: () => workspacesApiService.getWorkspace({ id: workspaceId }), enabled: !!workspaceId, }); const { mutateAsync: updateWorkspace, isPending: isSaving } = useAtomValue( updateWorkspaceMutationAtom ); const [customInstructions, setCustomInstructions] = useState(""); const hasWorkspace = !!workspace; const workspaceInstructions = workspace?.qna_custom_instructions; // Initialize state from fetched workspace useEffect(() => { if (hasWorkspace) { setCustomInstructions(workspaceInstructions || ""); } }, [hasWorkspace, workspaceInstructions]); // Derive hasChanges during render const hasChanges = !!workspace && (workspace.qna_custom_instructions || "") !== customInstructions; const handleSave = async () => { try { await updateWorkspace({ id: workspaceId, data: { qna_custom_instructions: customInstructions.trim() || "" }, }); toast.success("System instructions saved successfully"); } catch (error: unknown) { const message = error instanceof Error ? error.message : "Failed to save system instructions"; console.error("Error saving system instructions:", error); toast.error(message); } }; const onSubmit = (e: React.FormEvent) => { e.preventDefault(); handleSave(); }; if (loading) { return (