import { jsx } from "react/jsx-runtime";
import { useState } from "react";
import { connect, mapProps, mapReadPretty, useFieldSchema } from "@tachybase/schema";
import { fuzzysearch } from "@tachybase/utils/client";
import { useAsyncEffect } from "ahooks";
import { AutoComplete } from "antd";
import { useAPIClient } from "../../../api-client/index.mjs";
import { ReadPretty } from "../input/index.mjs";
const AutoComplete_AutoComplete = connect((props)=>{
    const { fieldNames, params: fieldFilter } = props;
    const fieldSchema = useFieldSchema();
    const targetKey = null == fieldNames ? void 0 : fieldNames.value;
    const api = useAPIClient();
    const [defultOptions, setDefultOptions] = useState([]);
    const [options, setOptions] = useState([]);
    const getNoDuplicateTextOptions = (rawOptions)=>{
        const targetOptions = rawOptions.filter((option, index, self)=>self.findIndex((item)=>item[targetKey] === option[targetKey]) === index);
        return targetOptions;
    };
    useAsyncEffect(async ()=>{
        const { data: { data: rawOptions } } = await api.request({
            url: fieldSchema['collectionName'] + ':list',
            params: {
                paginate: false,
                filter: fieldFilter ? {
                    ...fieldFilter.filter
                } : {}
            }
        });
        const targetOptions = getNoDuplicateTextOptions(rawOptions);
        setDefultOptions(targetOptions);
        setOptions(targetOptions);
    }, [
        null == fieldFilter ? void 0 : fieldFilter.filter,
        fieldSchema['collectionName']
    ]);
    const onSearch = (value)=>{
        value ? setOptions([
            {
                [targetKey]: value
            },
            ...defultOptions
        ]) : setOptions(defultOptions);
    };
    return /*#__PURE__*/ jsx(AutoComplete, {
        ...props,
        options: options,
        filterOption: (inputValue, option)=>{
            var _option_targetKey;
            return fuzzysearch(inputValue || '', (null == (_option_targetKey = option[targetKey]) ? void 0 : _option_targetKey.toString()) || '');
        },
        allowClear: true,
        onSearch: onSearch
    });
}, mapProps({
    dataSource: 'options'
}), mapReadPretty(ReadPretty.Input));
export { AutoComplete_AutoComplete as AutoComplete };
