import { getAccountUsers, IStrataAccountUser } from '@rh-support/api';
import { IContact } from 'hydrajs/types/src/models/contact';
import { IContactListParams } from 'hydrajs/types/src/models/contacts/contact';
import map from 'lodash/map';
import React, { useContext, useEffect, useState} from 'react';
import { Typeahead } from 'react-bootstrap-typeahead';
import { AppMetadataStateContext } from '../../context/AppMetadataContext';
import { CreateCaseDispatchContext, CreateCaseStateContext } from '../../context/CreateCaseContext';
import { setNotifiedUser } from '../../reducers/CreateCaseReducer';
import ContactSelect from '../shared/input/ContactSelect';

export interface IProps {}
export interface IAccountUser extends IStrataAccountUser { selectedLabel: string; }

export default function CaseContactSelector(props: IProps) {
    const { createCaseState } = useContext(CreateCaseStateContext);
    const [ strataAccountUsers, setStrataAccountUsers ] = useState<IAccountUser[]>([]);
    const [ strataAccountUsersLoading, setStrataAccountUsersLoading ] = useState<boolean>(true);
    const { selectedNotificationContacts} = createCaseState;
    const { appMetadataState: {
        loggedInUser,
        loggedInUserJwtToken: { account_number }
    } } = useContext(AppMetadataStateContext);
    const createCaseDispatch = useContext(CreateCaseDispatchContext);

    useEffect(() => {
        !loggedInUser.data.is_internal && loggedInUser.data.org_admin && getAccountUsers(account_number).then((response) => {
            setStrataAccountUsersLoading(true);
            const accountUsers = map(response.user, (user) => ({
                ...user,
                selectedLabel: `${user.first_name} ${user.last_name} (${user.sso_username})`
            }));
            setStrataAccountUsers(accountUsers);
        }).finally(() => {
            setStrataAccountUsersLoading(false);
        });
    }, []);

    const onNotifiedUserChange = (selectedContacts: IContact[]) => {
        setNotifiedUser(createCaseDispatch, selectedContacts);
    };
    const onInternalContactSelect = (contacts: IContact[]) => {
        onNotifiedUserChange(contacts || []);
    };
    const onCustomerContactSelect = (contacts: IAccountUser[]) => {
        const notifiedUsers: IContact[] = map(contacts, (c) => ({
            firstName: c.first_name,
            lastName: c.last_name,
            isOrgAdmin: c.org_admin,
            ssoUsername: c.sso_username
        }));
        onNotifiedUserChange(notifiedUsers);
    };

    const contactQueryParams: IContactListParams = loggedInUser.data.is_internal && {
        internal: false, // to get non-ldap contacts
        isInternalContact: true,
    };
    const renderMenuItemChildren = (option: IAccountUser) => (<span key={option.sso_username}>
        {option.selectedLabel}
    </span>);
    const selectedNotificationCustomerContacts: IAccountUser[] = !loggedInUser.data.is_internal && map(selectedNotificationContacts, (c) => ({
        first_name: c.firstName,
        last_name: c.lastName,
        org_admin: c.isOrgAdmin,
        sso_username: c.ssoUsername,
        selectedLabel: `${c.firstName} ${c.lastName} (${c.ssoUsername})`
    }));

    return (<div className="form-group">
        <label htmlFor="open-case-notifications">Send notifications</label>
        {loggedInUser.data.is_internal ? <ContactSelect
            selectedContacts={selectedNotificationContacts}
            id="open-case-notifications"
            name="open-case-notifications"
            multiple={true}
            contactListParams={contactQueryParams}
            placeholder={`Search for colleagues to notify`}
            onSelect={onInternalContactSelect} /> :
        <Typeahead
            id="open-case-notifications"
            name="open-case-notifications"
            className="react-select-custom"
            clearButton={true}
            isLoading={strataAccountUsersLoading}
            options={strataAccountUsers}
            selected={selectedNotificationCustomerContacts}
            onChange={onCustomerContactSelect}
            labelKey="selectedLabel"
            placeholder={`Search for colleagues to notify`}
            renderMenuItemChildren={renderMenuItemChildren}
            minLength={0}
            disabled={!loggedInUser.data.org_admin}
            multiple={true}
        />}
        <p className="form-instructions">{`${loggedInUser.data.org_admin ?
            'Include others from your account to receive case notifications.'
            : 'You need to be an organization admin to include others from your account.'}`}</p>
    </div>);
}
