"use client"; import { useQuery } from "@tanstack/react-query"; import { AlertTriangle, Info } from "lucide-react"; import { useEffect, useState } from "react"; import { toast } from "sonner"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; 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 { authenticatedFetch } from "@/lib/auth-utils"; 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, refetch: fetchSearchSpace, } = useQuery({ queryKey: cacheKeys.searchSpaces.detail(searchSpaceId.toString()), queryFn: () => searchSpacesApiService.getSearchSpace({ id: searchSpaceId }), enabled: !!searchSpaceId, }); const [customInstructions, setCustomInstructions] = useState(""); const [saving, setSaving] = useState(false); // Initialize state from fetched search space useEffect(() => { if (searchSpace) { setCustomInstructions(searchSpace.qna_custom_instructions || ""); } }, [searchSpace?.qna_custom_instructions]); // Derive hasChanges during render const hasChanges = !!searchSpace && (searchSpace.qna_custom_instructions || "") !== customInstructions; const handleSave = async () => { try { setSaving(true); const payload = { qna_custom_instructions: customInstructions.trim() || "", }; const response = await authenticatedFetch( `${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/searchspaces/${searchSpaceId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), } ); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.detail || "Failed to save system instructions"); } toast.success("System instructions saved successfully"); await fetchSearchSpace(); } catch (error: any) { console.error("Error saving system instructions:", error); toast.error(error.message || "Failed to save system instructions"); } finally { setSaving(false); } }; const onSubmit = (e: React.FormEvent) => { e.preventDefault(); handleSave(); }; if (loading) { return (