import { Box } from '@mui/material'; import { FC, useMemo, useState } from 'react'; import api from '../lib/api'; import Autocomplete from './Autocomplete'; import ContainedButton from './ContainedButton'; import EditFenceDeviceInputGroup from './EditFenceDeviceInputGroup'; import FlexBox from './FlexBox'; import handleAPIError from '../lib/handleAPIError'; import Spinner from './Spinner'; import { BodyText } from './Text'; import useIsFirstRender from '../hooks/useIsFirstRender'; import useProtectedState from '../hooks/useProtectedState'; type FenceDeviceAutocompleteOption = { fenceDeviceDescription: string; fenceDeviceId: string; label: string; }; const AddFenceDeviceForm: FC = () => { const isFirstRender = useIsFirstRender(); const [fenceDeviceTemplate, setFenceDeviceTemplate] = useProtectedState< APIFenceTemplate | undefined >(undefined); const [fenceDeviceTypeValue, setInputFenceDeviceTypeValue] = useState(null); const [isLoadingTemplate, setIsLoadingTemplate] = useProtectedState(true); const fenceDeviceTypeOptions = useMemo( () => fenceDeviceTemplate ? Object.entries(fenceDeviceTemplate).map( ([id, { description: rawDescription }]) => { const description = typeof rawDescription === 'string' ? rawDescription : 'No description.'; return { fenceDeviceDescription: description, fenceDeviceId: id, label: id, }; }, ) : [], [fenceDeviceTemplate], ); const fenceDeviceTypeElement = useMemo( () => ( option.fenceDeviceId === value.fenceDeviceId } label="Fence device type" onChange={(event, newFenceDeviceType) => { setInputFenceDeviceTypeValue(newFenceDeviceType); }} openOnFocus options={fenceDeviceTypeOptions} renderOption={( props, { fenceDeviceDescription, fenceDeviceId }, { selected }, ) => ( *': { width: '100%', }, }} {...props} > {fenceDeviceId} {fenceDeviceDescription} )} value={fenceDeviceTypeValue} /> ), [fenceDeviceTypeOptions, fenceDeviceTypeValue], ); const fenceParameterElements = useMemo( () => ( ), [fenceDeviceTemplate, fenceDeviceTypeValue], ); const formContent = useMemo( () => isLoadingTemplate ? ( ) : ( { event.preventDefault(); }} sx={{ '& > div': { marginBottom: 0 } }} > {fenceDeviceTypeElement} {fenceParameterElements} Add fence device ), [fenceDeviceTypeElement, fenceParameterElements, isLoadingTemplate], ); if (isFirstRender) { api .get(`/fence/template`) .then(({ data }) => { setFenceDeviceTemplate(data); }) .catch((error) => { handleAPIError(error); }) .finally(() => { setIsLoadingTemplate(false); }); } return <>{formContent}; }; export default AddFenceDeviceForm;