"use client"; import { PlusIcon } from "@heroicons/react/24/outline"; import { useEffect, useState } from "react"; import toast from "react-hot-toast"; import { useAppContext } from "../providers/AppContext"; import JsonInput from "./JsonInput"; import { useNotifications } from "./NotificationContext"; import QueueSettingsEditor from "./QueueSettingsEditor"; import SlideInForm from "./SlideInForm"; import WatcherSettingsEditor from "./WatcherSettingsEditor"; interface SettingsCrudProps { editKey?: string; editValue?: string; onEditClose?: () => void; } interface SettingsFormState { key: string; value: string; isOpen: boolean; } const initialSettingsState: SettingsFormState = { key: "", value: "", isOpen: false, }; export default function SettingsCrud({ editKey, editValue, onEditClose, }: SettingsCrudProps) { const { updateSetting } = useAppContext(); const { addNotification } = useNotifications(); const [formState, setFormState] = useState(initialSettingsState); const [isSaving, setIsSaving] = useState(false); const isEditing = !!editKey; useEffect(() => { if (isEditing) { setFormState({ key: editKey, value: editValue || "", isOpen: true, }); } }, [editKey, editValue, isEditing]); const handleSave = async () => { try { setIsSaving(true); await updateSetting(formState.key, formState.value); setFormState(initialSettingsState); if (onEditClose) onEditClose(); const message = isEditing ? "Setting updated successfully" : "Setting added successfully"; toast.success(message); addNotification({ type: "success", title: "Setting Saved", message: `${formState.key} has been ${isEditing ? "updated" : "added"} successfully.`, }); } catch (error) { console.error("Failed to save setting:", error); toast.error("Failed to save setting"); addNotification({ type: "error", title: "Save Failed", message: "Failed to save the setting. Please try again.", }); } finally { setIsSaving(false); } }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); handleSave(); }; const getValueEditor = (currentKey?: string) => { const editorKey = currentKey || formState.key; switch (editorKey) { case "watcher": return ( setFormState({ ...formState, value: val })} /> ); case "queue": return ( setFormState({ ...formState, value: val })} /> ); case "datasets": // Use JsonInput with JSON mode toggle for datasets configuration return ( setFormState({ ...formState, value: val })} className="w-full" placeholder="Datasets configuration (JSON)" /> ); default: return ( setFormState({ ...formState, value: val })} className="w-full" placeholder="Value (JSON)" /> ); } }; const handleClose = () => { setFormState(initialSettingsState); if (onEditClose) onEditClose(); }; if (isEditing) { return ( } >
setFormState({ ...formState, key: e.target.value }) } required disabled />
{getValueEditor()}
); } return ( <>
Add Setting
} >
setFormState({ ...formState, key: e.target.value }) } required />
{getValueEditor(formState.key)}
); }