import React, { useState } from 'react';
import { Button, FormField, Modal } from '@orchard/frontend-react-components';
import { ArtistDropdown } from 'frontend-participant-components';
import { formatMessage } from '@orchard/frontend-localization';
import Segment from 'src/utils/segment';
import { CollaboratorType } from 'src/__definitions__/globalTypes';
import { useCreateCollaboratorMutation, Collaborator } from 'src/mutations/create-collaborator';
import {
    SEGMENT_CATEGORIES,
    SEGMENT_EVENTS
} from 'src/constants';
import useIdentity from 'src/utils/use-identity';
import messages from './i18n';

type Participant = {
    name: string;
    participantId: string;
};

const CLASS_NAME = 'AddCollaboratorModal';

type Props = {
    subaccountId: string | null;
    onAdd(collaborator: Collaborator): void;
    onCancel(event: React.MouseEvent<HTMLButtonElement, MouseEvent>): void;
    vendorCurrencyCode: string;
};

const AddCollaboratorModal: React.FC<Props> = ({
    subaccountId,
    onAdd,
    onCancel,
    vendorCurrencyCode
}) => {
    const identity = useIdentity();

    const [participantValue, setParticipantValue] = useState<Participant>();
    const [artistDropdownError, setArtistDropdownError] = useState(false);

    const [
        createCollaboratorMutation,
        { error }
    ] = useCreateCollaboratorMutation();

    const handleAddCollaborator = async () => {
        let result;

        try {
            result = await createCollaboratorMutation({
                variables: {
                    name: participantValue!.name,
                    participantId: parseInt(participantValue!.participantId, 10),
                    subaccountId: subaccountId ? parseInt(subaccountId, 10) : null,
                    currency: vendorCurrencyCode,
                    collaboratorType: CollaboratorType.COLLABORATOR
                },
            });
        } catch {
            return;
        }

        if (!result.data?.createCollaborator)
            return;

        onAdd(result.data.createCollaborator);
    };

    const handleArtistDropdownChange = ([participant]: Participant[]) => {
        Segment.trackEvent(SEGMENT_EVENTS.SELECT_PARTICIPANT, SEGMENT_CATEGORIES.VIEW);

        setArtistDropdownError(false);
        setParticipantValue(participant);
    };

    const handleArtistDropdownError = () => {
        setArtistDropdownError(true);
    };

    return (
        // @ts-ignore <Modal> is requiring unrequired types
        <Modal
            className={ `${CLASS_NAME}` }
            onRequestClose={ onCancel }
            headerLabel={ formatMessage(messages.addNewCollaborator) }
            isOpen
            footer={ (
                <div className={ `${CLASS_NAME}-footer-buttons` }>
                    { error
                            && (
                                <span className={ `${CLASS_NAME}-footer-error` }>
                                    { formatMessage(messages.savingError) }
                                </span>
                            ) }
                    <Button
                        className={ `${CLASS_NAME}-footer-button-cancel` }
                        type="button"
                        onClick={ onCancel }
                        aria-label={ formatMessage(messages.cancel) }
                        data-testid="add-collaborator-cancel-button"
                    >
                        { formatMessage(messages.cancel) }
                    </Button>
                    <Button
                        className={ `${CLASS_NAME}-footer-button-add` }
                        type="button"
                        variant="primary"
                        onClick={ handleAddCollaborator }
                        aria-label={ formatMessage(messages.add) }
                        data-testid="add-collaborator-button"
                        disabled={ !participantValue }
                    >
                        { formatMessage(messages.add) }
                    </Button>
                </div>
            ) }
        >
            <div className={ `${CLASS_NAME}-content` }>
                <div className={ `${CLASS_NAME}-form-field` }>
                    <FormField
                        errorMessage={ artistDropdownError
                            && formatMessage(messages.savingError) }
                    >
                        <label htmlFor="add-name" id="add-name-label">
                            <span className={ `${CLASS_NAME}-form-label` }>
                                { formatMessage(messages.name) }
                            </span>
                            <ArtistDropdown
                                multi={ false }
                                placeholder={ formatMessage(messages.searchCollaborator) }
                                vendorId={ identity.vendorId }
                                subaccountId={ subaccountId ? parseInt(subaccountId, 10) : 0 }
                                isParticipantProfilesNeo4jSearchEnabled={ true }
                                isParticipantProfilesNeo4jCreateEnabled={ true }
                                onChange={ handleArtistDropdownChange }
                                onMutationError={ handleArtistDropdownError }
                                value={ participantValue ? [participantValue] : [] }
                            />
                        </label>
                    </FormField>
                </div>
            </div>
        </Modal>
    );
};

export default AddCollaboratorModal;
