import React, { PureComponent } from 'react';
import { makeCancelable } from '../../utils/cancelablePromise';
import noop from '../../utils/noop';
import ArtistPopover from '../artistPopover/artistPopoverDigital';
import type { ArtistStoreProfile } from '../../types';
import type { CancelablePromise } from '../../utils/cancelablePromise';

export interface Props {
    data: object;
    selectProps: {
        onProfilesFetch?: (data: object) => Promise<ArtistStoreProfile[]>;
        onEditIncorrectArtist?: (data: object) => void;
    };
}

interface State {
    isFetchExecuted: boolean;
    isLoading: boolean;
    profiles: ArtistStoreProfile[];
}

export default class ArtistMultiValue extends PureComponent<Props, State> {
    cancelablePromise?: CancelablePromise<ArtistStoreProfile[]>;

    constructor(props: Props) {
        super(props);
        this.state = {
            profiles: [],
            isLoading: true,
            isFetchExecuted: false,
        };
    }

    componentWillUnmount() {
        if (this.cancelablePromise) this.cancelablePromise.cancel();
    }

    handleOpen = async () => {
        const {
            data,
            selectProps: { onProfilesFetch },
        } = this.props;
        const { isFetchExecuted } = this.state;
        if (isFetchExecuted) return undefined;

        if (onProfilesFetch) {
            this.setState({ isFetchExecuted: true });
            this.cancelablePromise = makeCancelable(onProfilesFetch(data));
            return await this.cancelablePromise.promise
                .then((profiles) => this.setState({ isLoading: false, profiles }))
                .catch(noop);
        }

        return undefined;
    };

    handleEditIncorrectArtist = () => {
        const {
            data,
            selectProps: { onEditIncorrectArtist },
        } = this.props;
        if (onEditIncorrectArtist) onEditIncorrectArtist(data);
    };

    render() {
        const { profiles, isLoading } = this.state;
        return (
            <ArtistPopover
                id="artistPopover"
                profiles={profiles}
                isLoading={isLoading}
                onOpen={this.handleOpen}
                onEditIncorrectArtist={this.handleEditIncorrectArtist}
            >
                <div />
            </ArtistPopover>
        );
    }
}
