import React from "react";
import { AutoComplete, Spin } from "antd";
import { useModels } from "../../hooks";

const AsyncAutocompleteGuidelineGroup = ({
  name,
  expand = "",
  labelProp,
  index,
  defaultVal = null,
  onSelect,
  paramsValues = "id",
  extraParams,
  searchParam = "",
  disabled = false,
  notFoundContent = "No hay opciones disponibles.",
  size,
  placeholder="Buscar por nombre...",
  ...rest
}) => {
  const [open, setOpen] = React.useState(false)
  const [options, setOptions] = React.useState([])
  
  const [
    models,
    modelsLoading,
    modelsError,
    modelsPage,
    modelsRefresh,
  ] = useModels({
    name,
    extraParams,
    expand,
  });

  React.useEffect(() => {
    if(models && !modelsLoading){
      let arr = []

      models.forEach(m => {
        arr = [ 
          ...arr, 
          {
            value: `[${m?.id || "Sin definir"}] - ${m?.nombre || "Sin definir"}`,
            obj: m       
          }
        ]
      })
      setOptions(arr)
    }
  }, [models, modelsLoading])

  const refreshSearch = React.useCallback(
    async (params) => {
      await modelsRefresh(true, params);
    },
    [modelsRefresh]
  );

  const onKeyPressCallback = async (e) => {
    let params = {
      [searchParam !== "" ? searchParam : labelProp]: e.target.value,
    };
    await refreshSearch(params);
  };

  return (
    <AutoComplete
      allowClear={true}
      placeholder={placeholder}
      disabled={disabled}
      id="autocomplete-test"
      size={size}
      style={{width: "100%"}}
      open={open}
      onDropdownVisibleChange={() => setOpen(op => !op)}
      notFoundContent={
        modelsLoading ? <Spin /> : notFoundContent 
      }
      options={options}
      onKeyUp={onKeyPressCallback}
      onSelect={(val, opt) => {
        isNaN(index) 
          ? onSelect(val, opt) 
          : onSelect(val, opt, index);
      }}
      defaultValue={defaultVal}
    />
  )
}

export default AsyncAutocompleteGuidelineGroup