import { Box } from '@mui/material'; import { FC, useMemo, useState } from 'react'; import api from '../lib/api'; import Autocomplete from './Autocomplete'; import CommonFenceInputGroup from './CommonFenceInputGroup'; 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 FenceAutocompleteOption = { fenceDescription: string; fenceId: string; label: string; }; const AddFenceInputGroup: FC = () => { const isFirstRender = useIsFirstRender(); const [fenceTemplate, setFenceTemplate] = useProtectedState< APIFenceTemplate | undefined >(undefined); const [fenceTypeValue, setInputFenceTypeValue] = useState(null); const [isLoadingTemplate, setIsLoadingTemplate] = useProtectedState(true); const fenceTypeOptions = useMemo( () => fenceTemplate ? Object.entries(fenceTemplate).map( ([id, { description: rawDescription }]) => { const description = typeof rawDescription === 'string' ? rawDescription : 'No description.'; return { fenceDescription: description, fenceId: id, label: id, }; }, ) : [], [fenceTemplate], ); const fenceTypeElement = useMemo( () => ( option.fenceId === value.fenceId } label="Fence device type" onChange={(event, newFenceType) => { setInputFenceTypeValue(newFenceType); }} openOnFocus options={fenceTypeOptions} renderOption={(props, { fenceDescription, fenceId }, { selected }) => ( *': { width: '100%', }, }} {...props} > {fenceId} {fenceDescription} )} value={fenceTypeValue} /> ), [fenceTypeOptions, fenceTypeValue], ); const fenceParameterElements = useMemo( () => ( ), [fenceTemplate, fenceTypeValue], ); const formContent = useMemo( () => isLoadingTemplate ? ( ) : ( div': { marginBottom: 0 } }}> {fenceTypeElement} {fenceParameterElements} ), [fenceTypeElement, fenceParameterElements, isLoadingTemplate], ); if (isFirstRender) { api .get(`/fence/template`) .then(({ data }) => { setFenceTemplate(data); }) .catch((error) => { handleAPIError(error); }) .finally(() => { setIsLoadingTemplate(false); }); } return <>{formContent}; }; export default AddFenceInputGroup;