"use client"; import { useState } from "react"; import { Plus, Check, Loader2, Eye, EyeOff, ChevronDown, TestTube, } from "lucide-react"; import { apiUrl } from "@/lib/api"; import { ConfigItem, ConfigType } from "../types"; import { PROVIDER_OPTIONS, LOCAL_PROVIDERS, LOCAL_PROVIDER_URLS, VOICE_OPTIONS, getEnvVarForBaseUrl, getEnvVarForApiKey, } from "../constants"; interface ConfigFormProps { configType: ConfigType; showDimensions: boolean; showVoice: boolean; isSearchConfig: boolean; editConfig?: ConfigItem | null; t: (key: string) => string; onSuccess: () => void; onCancel: () => void; } export default function ConfigForm({ configType, showDimensions, showVoice, isSearchConfig, editConfig, t, onSuccess, onCancel, }: ConfigFormProps) { const isEditMode = !!editConfig; const [saving, setSaving] = useState(false); const [testing, setTesting] = useState(false); const [error, setError] = useState(null); const [testResult, setTestResult] = useState<{ success: boolean; message: string; } | null>(null); // Helper to check if a value uses env reference format const isEnvReference = (value: any): boolean => { return !!(value && typeof value === "object" && "use_env" in value); }; // Helper to get display value const getDisplayValue = (value: any): string => { if (isEnvReference(value)) return ""; return typeof value === "string" ? value : ""; }; // Check initial env reference states const initialUseEnvBaseUrl = editConfig ? isEnvReference(editConfig.base_url) : false; const initialUseEnvApiKey = editConfig ? isEnvReference(editConfig.api_key) : false; // Form state const [name, setName] = useState(editConfig?.name || ""); const [provider, setProvider] = useState( editConfig?.provider || PROVIDER_OPTIONS[configType][0], ); const [baseUrl, setBaseUrl] = useState( editConfig ? getDisplayValue(editConfig.base_url) : "", ); const [useEnvBaseUrl, setUseEnvBaseUrl] = useState(initialUseEnvBaseUrl); const [apiKey, setApiKey] = useState(""); const [useEnvApiKey, setUseEnvApiKey] = useState(initialUseEnvApiKey); const [showApiKey, setShowApiKey] = useState(false); const [model, setModel] = useState(editConfig?.model || ""); const [dimensions, setDimensions] = useState(editConfig?.dimensions || 3072); const [voice, setVoice] = useState(editConfig?.voice || "alloy"); const isLocalProvider = LOCAL_PROVIDERS.includes(provider); const handleProviderChange = (newProvider: string) => { setProvider(newProvider); if ( LOCAL_PROVIDERS.includes(newProvider) && LOCAL_PROVIDER_URLS[newProvider] ) { setBaseUrl(LOCAL_PROVIDER_URLS[newProvider]); setUseEnvBaseUrl(false); setUseEnvApiKey(false); setApiKey(""); } }; const handleTestConnection = async () => { if (isSearchConfig) return; if (!useEnvBaseUrl && !baseUrl) { setTestResult({ success: false, message: t("Base URL is required for testing"), }); return; } if (!isLocalProvider && !useEnvApiKey && !apiKey) { setTestResult({ success: false, message: t("API Key is required for cloud providers"), }); return; } if (!model) { setTestResult({ success: false, message: t("Model name is required") }); return; } if (configType === "embedding" && !dimensions) { setTestResult({ success: false, message: t("Dimensions is required for embedding models"), }); return; } setTesting(true); setTestResult(null); try { const res = await fetch(apiUrl(`/api/v1/config/${configType}/test`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider, base_url: useEnvBaseUrl ? { use_env: getEnvVarForBaseUrl(configType) } : baseUrl, api_key: isLocalProvider ? "" : useEnvApiKey ? { use_env: getEnvVarForApiKey(configType) } : apiKey, model, ...(configType === "embedding" ? { dimensions: Number(dimensions) } : {}), ...(configType === "tts" && voice ? { voice } : {}), }), }); const data = await res.json(); setTestResult({ success: data.success ?? false, message: data.message || (data.success ? t("Connection successful") : t("Connection failed")), }); } catch (e: any) { setTestResult({ success: false, message: e?.message || t("Connection test failed - network error"), }); } finally { setTesting(false); } }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setSaving(true); setError(null); try { const payload: Record = { name, provider, api_key: isLocalProvider ? apiKey || "" : useEnvApiKey ? { use_env: getEnvVarForApiKey(configType) } : apiKey, }; if (!isSearchConfig) { payload.base_url = useEnvBaseUrl ? { use_env: getEnvVarForBaseUrl(configType) } : baseUrl; payload.model = model; } if (showDimensions) { payload.dimensions = dimensions; } if (showVoice) { payload.voice = voice; } const url = isEditMode ? apiUrl(`/api/v1/config/${configType}/${editConfig.id}`) : apiUrl(`/api/v1/config/${configType}`); const method = isEditMode ? "PUT" : "POST"; const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); if (res.ok) { onSuccess(); } else { const data = await res.json(); setError( data.detail || (isEditMode ? t("Failed to update configuration") : t("Failed to add configuration")), ); } } catch (e) { setError( isEditMode ? t("Failed to update configuration") : t("Failed to add configuration"), ); } finally { setSaving(false); } }; return (

{isEditMode ? `${t("Edit Configuration")}: ${editConfig.name}` : t("Add New Configuration")}

{error && (
{error}
)} {testResult && (
{testResult.message}
)}
{/* Name */}
setName(e.target.value)} required placeholder={t("My Configuration")} className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
{/* Provider */}
{/* Base URL (not for search) */} {!isSearchConfig && (
setBaseUrl(e.target.value)} disabled={useEnvBaseUrl} placeholder={ useEnvBaseUrl ? `Using ${getEnvVarForBaseUrl(configType)} from .env` : "https://api.openai.com/v1" } className={`w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent ${ useEnvBaseUrl ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 text-blue-600 dark:text-blue-400 italic" : "bg-white dark:bg-slate-800 border-slate-300 dark:border-slate-600" }`} />
)} {/* API Key */}
setApiKey(e.target.value)} disabled={useEnvApiKey} placeholder={ isLocalProvider ? t("Not required") : useEnvApiKey ? `Using ${getEnvVarForApiKey(configType)} from .env` : "sk-..." } className={`w-full px-3 py-2 pr-10 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent ${ useEnvApiKey ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 text-blue-600 dark:text-blue-400 italic" : "bg-white dark:bg-slate-800 border-slate-300 dark:border-slate-600" }`} /> {!useEnvApiKey && ( )}
{!isLocalProvider && ( )}
{/* Model (not for search) */} {!isSearchConfig && (
setModel(e.target.value)} required placeholder={t("gpt-4o")} className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
)} {/* Dimensions (embedding only) */} {showDimensions && (
setDimensions(parseInt(e.target.value, 10))} className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
)} {/* Voice (TTS only) */} {showVoice && (
)}
{/* Actions */}
{!isSearchConfig && ( )}
); }