"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 { updateSearchSpaceMutationAtom } from "@/atoms/search-spaces/search-space-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 { searchSpacesApiService } from "@/lib/apis/search-spaces-api.service"; import { cacheKeys } from "@/lib/query-client/cache-keys"; import { Spinner } from "../ui/spinner"; interface PromptConfigManagerProps { searchSpaceId: number; } export function PromptConfigManager({ searchSpaceId }: PromptConfigManagerProps) { const { data: searchSpace, isLoading: loading, } = useQuery({ queryKey: cacheKeys.searchSpaces.detail(searchSpaceId.toString()), queryFn: () => searchSpacesApiService.getSearchSpace({ id: searchSpaceId }), enabled: !!searchSpaceId, }); const { mutateAsync: updateSearchSpace, isPending: isSaving } = useAtomValue( updateSearchSpaceMutationAtom ); const [customInstructions, setCustomInstructions] = useState(""); const hasSearchSpace = !!searchSpace; const searchSpaceInstructions = searchSpace?.qna_custom_instructions; // Initialize state from fetched search space useEffect(() => { if (hasSearchSpace) { setCustomInstructions(searchSpaceInstructions || ""); } }, [hasSearchSpace, searchSpaceInstructions]); // Derive hasChanges during render const hasChanges = !!searchSpace && (searchSpace.qna_custom_instructions || "") !== customInstructions; const handleSave = async () => { try { await updateSearchSpace({ id: searchSpaceId, 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 (