import * as React from 'react';
import {Select} from './Select';
import {IOption} from './Select.types';

interface IProps {
    value: string | number;
    onChange: (value: IOption) => void;
    options: () => Promise<IOption[]>;
}

interface IState {
    isLoading: boolean;
    options: IOption[];
}

export class SelectLookup extends React.Component<IProps, IState> {
    override state = {
        isLoading: false,
        options: []
    };

    override componentDidMount (): void {
        this.setState({isLoading: true});

        this.props.options()
            .then((options) => {
                this.setState({options, isLoading: false});
            })
            .catch((err) => {
                console.error(err);
                this.setState({isLoading: false});
            });
    }

    onChange = (value: string) => {
        const option = this.state.options.find((item: any) => item.value === value);

        if (option !== undefined) {
            this.props.onChange(option);
        }
    };

    override render () {
        return (
            <Select
                showSearch={true}
                value={this.props.value}
                options={this.state.options}
                onChange={this.onChange}
                defaultActiveFirstOption={false}
                data-qaid='selectLookup'
                // notFoundContent={this.state.isLoading === true ? <Spinner/> : null}
            />
        );
    }
}
