import React, { useState, useMemo, useEffect } from "react"
import {Select} from "antd"
import debounce from 'lodash/debounce';

const {Option} = Select

const SelectUser:React.FC=(props)=>{

    const {value,onChange,users,type,loading} = props

    const [searchValue, setSearchValue] = useState(undefined)

    const debounceFetcher = useMemo(() => {
        return debounce((value) => {
            setSearchValue(value);
        }, 800);
      }, []);

    const filterUsers = useMemo(() => {
        if (searchValue) {
            return users?.filter(item => item.nachn?.includes(searchValue) || item.pernr?.includes(searchValue));
        } 
        
        return users||[];
    }, [users, searchValue])  

    const change=(value)=>{
        onChange&&onChange(value)
    }

    if(type==='edit'){
        return(
            <Select 
                style={{width:'100%'}}
                showSearch
                value={value}
                onChange={change}
                loading={loading}
                allowClear
                filterOption={false}
                onSearch={debounceFetcher}
            >
                {
                    filterUsers?.map((item)=>{
                        return(
                            <Option value={item.pernr} key={item.pernr}>{`${item.nachn}(${item.pernr})`}</Option>
                        )
                    })
                }
            </Select>
        )
    }else if(type==='detail'){
        try {
            const user = users?.filter((item)=>(item.pernr===value))
            return `${user[0].nachn}(${user[0].pernr})`;
        } catch (error) {
            return value
        }
    }else{
        return null
    }
}   

export default SelectUser