import React from 'react';
import { formatMessage } from '@theorchard/suite-i18n';
import { GlyphIcon } from '@theorchard/suite-icons';
import { components } from 'react-select';
import type { LoadOptionsHandler } from './types';
import type { DropdownOption } from '../dropdown/types';
import type { DropdownIndicatorProps, GroupBase, OptionsOrGroups, Props } from 'react-select';

export const IndicatorSeparator = () => null;

export function DropdownIndicator<
    T extends DropdownOption,
    M extends boolean,
    G extends GroupBase<T>,
>(props: DropdownIndicatorProps<T, M, G>) {
    return (
        <components.DropdownIndicator {...props}>
            <GlyphIcon name="search" size={16} />
        </components.DropdownIndicator>
    );
}

export const defaultNoOptionsMessage: Props['noOptionsMessage'] = ({ inputValue }) => {
    if (!inputValue) return null;
    return formatMessage('no_matching_options');
};

export function createLoadOptionsHandler<
    T extends DropdownOption = DropdownOption,
    G extends GroupBase<T> = GroupBase<T>,
>(handler: LoadOptionsHandler<T, G>) {
    return (term: string, callback: (options: OptionsOrGroups<T, G>) => void) => {
        handler(term)
            .then((result) => callback(result))
            .catch((error) => {
                // eslint-disable-next-line no-console
                console.error(error);

                callback([
                    {
                        value: 'error',
                        label: formatMessage('error_generic_title'),
                        disabled: true,
                        className: 'error',
                    } as T,
                ]);
            });
    };
}
