import React, { useRef } from 'react'; import { useTranslation } from 'react-i18next'; import userService from '../api/services/userService'; import { useOutsideAlerter } from '../hooks'; import { ActiveState } from '../models/misc'; import ConfigToolModal from './ConfigToolModal'; import { AvailableToolType } from './types'; import Spinner from '../components/Spinner'; import WrapperComponent from './WrapperModal'; export default function AddToolModal({ message, modalState, setModalState, getUserTools, onToolAdded, }: { message: string; modalState: ActiveState; setModalState: (state: ActiveState) => void; getUserTools: () => void; onToolAdded: (toolId: string) => void; }) { const { t } = useTranslation(); const modalRef = useRef(null); const [availableTools, setAvailableTools] = React.useState< AvailableToolType[] >([]); const [selectedTool, setSelectedTool] = React.useState(null); const [configModalState, setConfigModalState] = React.useState('INACTIVE'); const [loading, setLoading] = React.useState(false); useOutsideAlerter(modalRef, () => { if (modalState === 'ACTIVE') { setModalState('INACTIVE'); } }, [modalState]); const getAvailableTools = () => { setLoading(true); userService .getAvailableTools() .then((res) => { return res.json(); }) .then((data) => { setAvailableTools(data.data); setLoading(false); }); }; const handleAddTool = (tool: AvailableToolType) => { if (Object.keys(tool.configRequirements).length === 0) { userService .createTool({ name: tool.name, displayName: tool.displayName, description: tool.description, config: {}, actions: tool.actions, status: true, }) .then((res) => { if (res.status === 200) { return res.json(); } else { throw new Error( `Failed to create tool, status code: ${res.status}`, ); } }) .then((data) => { getUserTools(); setModalState('INACTIVE'); onToolAdded(data.id); }) .catch((error) => { console.error('Failed to create tool:', error); }); } else { setModalState('INACTIVE'); setConfigModalState('ACTIVE'); } }; React.useEffect(() => { if (modalState === 'ACTIVE') getAvailableTools(); }, [modalState]); return ( <> {modalState === 'ACTIVE' && ( setModalState('INACTIVE')} className="h-[85vh] w-[90vw] md:w-[75vw]" >

{t('settings.tools.selectToolSetup')}

{loading ? (
) : ( availableTools.map((tool, index) => (
{ setSelectedTool(tool); handleAddTool(tool); }} onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { setSelectedTool(tool); handleAddTool(tool); } }} >

{tool.displayName}

{tool.description}

)) )}
)} ); }