import { useCallback , useState } from "react" ; import { useDispatch } from "react-redux" ; import { getAllFacilities , getPermittedFacilities } from "../../Redux/actions" ; import { AutoCompleteAsyncField } from "../Common/HelperInputFields" ; import { FacilityModel } from "../Facility/models" ; const debounce = require ( "lodash.debounce" ) ; interface FacilitySelectProps { name : string ; margin ? : string ; errors : string ; className ? : string ; searchAll ? : boolean ; multiple ? : boolean ; facilityType ? : number ; showAll ? : boolean ; selected : FacilityModel | FacilityModel [ ] | null ; setSelected : ( selected : FacilityModel | FacilityModel [ ] | null ) => void ; } export const FacilitySelect = ( props ) => { const { name , multiple , selected , setSelected , margin , errors , searchAll , showAll = true , className = "" , facilityType , } = props ; const dispatchAction = useDispatch ( ) ; const [ facilityLoading , isFacilityLoading ] = useState ( false ) ; const [ hasSearchText , setHasSearchText ] = useState ( false ) ; const [ facilityList , setFacilityList ] = useState < Array < FacilityModel > > ( [ ] ) ; const handleValueChange = ( current ) => { if ( ! current ) { setFacilityList ( [ ] ) ; isFacilityLoading ( false ) ; setHasSearchText ( false ) ; } setSelected ( current ) ; } ; const handelSearch = ( e ) => { isFacilityLoading ( true ) ; setHasSearchText ( ! ! e . target . value ) ; onFacilitySearch ( e . target . value ) ; } ; const onFacilitySearch = useCallback ( debounce ( async ( text ) => { if ( text ) { const params = { limit : 50 , offset : 0 , search_text : text , all : searchAll , facility_type : facilityType , } ; const res = await dispatchAction ( showAll ? getAllFacilities ( params ) : getPermittedFacilities ( params ) ) ; if ( res && res . data ) { setFacilityList ( res . data . results ) ; } isFacilityLoading ( false ) ; } else { setFacilityList ( [ ] ) ; isFacilityLoading ( false ) ; } } , 300 ) , [ ] ) ; return ( < AutoCompleteAsyncField name = { name } multiple = { multiple } variant = "outlined" margin = { margin } value = { selected } options = { facilityList } onSearch = { handelSearch } onChange = { ( e , selected ) => handleValueChange ( selected ) } loading = { facilityLoading } placeholder = "Search by facility name or by district" noOptionsText = { hasSearchText ? "No facility found, please try again" : "Start typing to begin search" } renderOption = { ( option ) => ( < div > { option . name } { option . district_object ? `, ${ option . district_object . name }` : "" } < /div>)} getOptionSelected={(option, value) => option.id === value.id} getOptionLabel={(option) => option.name + ( option . district_object ? `, ${ option . district_object . name }` : "" ) } filterOptions = { ( options ) => options } errors = { errors } className = { className } / > ) ; } ;