import { Box } from '@mui/material'; import { FC, useMemo, useState } from 'react'; import useIsFirstRender from '../hooks/useIsFirstRender'; import useProtectedState from '../hooks/useProtectedState'; import api from '../lib/api'; import handleAPIError from '../lib/handleAPIError'; import Autocomplete from './Autocomplete'; import FlexBox from './FlexBox'; import Spinner from './Spinner'; import { BodyText } from './Text'; type FenceDeviceAutocompleteOption = { fenceDeviceDescription: string; fenceDeviceId: string; label: string; }; const AddFenceDeivceForm: FC = () => { const isFirstRender = useIsFirstRender(); const [fenceDeviceTemplate, setFenceDeviceTemplate] = useProtectedState< APIFenceTemplate | undefined >(undefined); const [inputFenceDeviceTypeValue, 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 autocompleteFenceDeviceType = 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={inputFenceDeviceTypeValue} /> ), [fenceDeviceTypeOptions, inputFenceDeviceTypeValue], ); const formContent = useMemo( () => isLoadingTemplate ? ( ) : ( <>{autocompleteFenceDeviceType} ), [autocompleteFenceDeviceType, isLoadingTemplate], ); if (isFirstRender) { api .get(`/fence/template`) .then(({ data }) => { setFenceDeviceTemplate(data); }) .catch((error) => { handleAPIError(error); }) .finally(() => { setIsLoadingTemplate(false); }); } return {formContent}; }; export default AddFenceDeivceForm;