import {
 Autocomplete, TextField
} from '@mui/material';
import * as React from 'react';
import Select, { SelectChangeEvent } from '@mui/material/Select';
import {useIntl } from "react-intl";

export default function Combo ({valueName, disabled, form, dataList, filterOptions, getOptionLabel, isOptionEqualToValue, onInputChange, onChange, ...props}){
    const [value, setValue] = React.useState(form.values[valueName]);
    const [inputValue, setInputValue] = React.useState("");
    const intl = useIntl();

    return (
        <Autocomplete
            {...props}
            disablePortal
            fullWidth
            id={valueName}
            name={valueName}
            disabled={disabled}
            value={value}
            inputValue={inputValue}
            filterOptions={filterOptions}
            options={dataList}
            getOptionLabel={(opt) => {
                if (opt == null) return "";
                let v;
                try {
                    v = getOptionLabel ? getOptionLabel(opt) : String(opt);
                } catch {
                    v = "";
                }
                if (v == null) return "";
                return typeof v === "string" ? v : String(v);
            }}
            isOptionEqualToValue={(option, newValue)=>{
                if(isOptionEqualToValue)
                    isOptionEqualToValue(option,newValue, setValue,setInputValue )
            }}
            onInputChange={(event, newValue) => {
                setInputValue(newValue);
                if(onInputChange){
                    onInputChange(event,newValue, setInputValue)
                }
            }}
            onChange={(event, newValue) => {
                setValue(newValue);
                if (!onChange){
                    form.setFieldValue(valueName, newValue);
                }else{
                    onChange(event, newValue);
                }
            }}
            sx={{
                '& .MuiInputBase-root': { alignItems: 'center' },
                '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                '& .MuiOutlinedInput-root': { height: 40 },
                "& .MuiInputBase-input.Mui-disabled": {
                    WebkitTextFillColor: "#000000",
                    background: "#f8f8f8",
                },
            }}
            renderInput={(params) => <TextField {...params} sx={{
                "& .MuiInputBase-input.Mui-disabled": {
                  WebkitTextFillColor: "#000000",
                  background: "#f8f8f8",
                },
            }}/>}
            clearText={intl.formatMessage({ id: "muiClear" })}
            closeText={intl.formatMessage({ id: "muiClose" })}
            openText={intl.formatMessage({ id: "muiOpen" })}
            noOptionsText={intl.formatMessage({ id: "muiNoOptions" })}
        />
    );
}