import React, { useEffect, useRef, useState } from 'react';
import { Autocomplete, TextField } from '@mui/material';
import debounce from 'lodash.debounce';

//
// Ver: https://github.com/mui-org/material-ui/blob/v5.2.0/docs/src/pages/components/autocomplete/GoogleMaps.js
//

const ModelAutocomplete = ({
  label,
  model,
  value,
  onChange,
  required,
  multiple,
  error,
  helperText,
  q,
}) => {
  const [inputValue, setInputValue] = useState('');
  const [options, setOptions] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const fetchData = (inputValue, q) => model.search(inputValue, q)
    .then(setOptions)
    .catch(setOptions)
    .then(() => setIsLoading(false));

  const debounced = useRef(debounce(fetchData, 1000, {
    leading: false,
    trailing: true,
    maxWait: 3000,
  }));

  useEffect(() => {
    setIsLoading(true);
    debounced.current(inputValue.trim(), q);
  }, [q, inputValue]);

  const getOptionLabel = option => (
    model.schema.getOptionLabel
      ? model.schema.getOptionLabel(option)
      : model.schema.searchProps.map((propName) => {
        const parts = propName.split('.');
        if (parts.length > 1) {
          return option[parts[0]][parts[1]];
        }
        return option[propName];
      }).join(' / ')
  );

  if (options instanceof Error) {
    window.alert('Error loading options');
  }

  return (
    <Autocomplete
      loading={isLoading}
      multiple={multiple}
      getOptionLabel={getOptionLabel}
      filterOptions={x => x}
      options={options instanceof Error ? [] : options}
      required={!!required}
      renderInput={params => (
        <TextField
          {...params}
          label={label}
          error={error}
          helperText={helperText}
          required={!!required}
        // focused={!!error}
        // inputRef={input => input && error && input.focus()}
        />
      )}
      inputValue={inputValue}
      onInputChange={(_, newInputValue) => {
        setInputValue(newInputValue);
      }}
      value={value}
      onChange={(_, newValue) => {
        onChange(newValue);
      }}
    />
  );
};

export default ModelAutocomplete;