"use client";
import debounce from "lodash.debounce";
import AsyncSelect from "react-select/async";

import { AutoCompleteProps, callback } from "../types";

export type { AutoCompleteProps } from "../types";

const AutoComplete = ({
  defaultValue,
  searchFn,
  limit = 10,
  name,
  placeholder,
  slugAsValue = false,
  acceptMultiple = false,
  readOnly = false,
  required = false,
  ...props
}: AutoCompleteProps) => {
  const loadOptions = debounce((inputValue: string, callback: callback) => {
    if (inputValue.length >= 2 || inputValue.length === 0) {
      searchFn(inputValue).then((options) => {
        if (options)
          callback(
            options.slice(0, limit).map((option: any) => ({
              label: option.title,
              value: slugAsValue ? option.slug : option.id
            }))
          );
      });
    }
  }, 100);

  return (
    <AsyncSelect
      id={name}
      name={name}
      placeholder={placeholder}
      loadingMessage={({ inputValue }) =>
        inputValue.length < 2 ? "Please type at least 2 characters" : "Loading..."
      }
      loadOptions={loadOptions}
      defaultValue={defaultValue as any}
      cacheOptions
      defaultOptions
      isMulti={acceptMultiple}
      isDisabled={readOnly}
      {...props}
      required={required}
    />
  );
};

export default AutoComplete;
