import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete, { createFilterOptions } from '@mui/material/Autocomplete';
import CircularProgress from '@mui/material/CircularProgress';

export default function SearchSelect({
  label = "",
  value = "",
  setValue = () => { },
  getData = () => new Promise(),
  research = false,
}) {
  const [open, setOpen] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [inputValue, setInputValue] = React.useState("");
  const [options, setOptions] = React.useState([]);
  const [searchComplete, setSearchComplete] = React.useState(false);

  React.useEffect(() => {
    if (!loading || searchComplete) {
      return undefined;
    }

    const debounce = setTimeout(async () => {
      const data = await getData(inputValue);
      setOptions(data);
      if (!research) setSearchComplete(true);
    }, research ? 500 : 0); // reduce queries while typing

    return () => {
      clearTimeout(debounce);
    };
  }, [research, loading, inputValue, getData, setOptions, searchComplete, setSearchComplete]);

  React.useEffect(() => {
    if (!research || searchComplete) {
      return undefined;
    }

    setOptions([]);
  }, [research, open, inputValue, setOptions, searchComplete]);

  React.useEffect(() => {
    if (searchComplete) {
      return undefined;
    }

    setLoading(open && options.length === 0);
    const timeout = setTimeout(() => {
      setLoading(false);
    }, 2000); // don't show loading forever

    return () => {
      clearTimeout(timeout);
    }
  }, [searchComplete, open, options, setLoading]);

  return (
    <Autocomplete
      fullWidth
      value={value}
      onChange={(_, value) => setValue(value)}
      inputValue={inputValue}
      onInputChange={(_, inputValue) => setInputValue(inputValue)}
      open={open}
      onOpen={() => setOpen(true)}
      onClose={() => setOpen(false)}
      options={options}
      loading={loading}
      filterOptions={research ? (x) => x : createFilterOptions()}
      renderInput={(params) =>
        <TextField
          {...params}
          label={label}
          name={label}
          variant="outlined"
          margin="normal"
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <React.Fragment>
                {loading ? <CircularProgress color="inherit" size={20} /> : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
        />
      }
    />
  );
}