import { IStrataEntitlement } from '@rh-support/api';
import { IDClassNameProps, IOption } from '@rh-support/types';
import { toOption, toOptions } from '@rh-support/utils';
import { Popover, PopoverPosition } from '@patternfly/react-core/dist/js/components/Popover';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import React, { useContext, useState } from 'react';
import { AppMetadataStateContext } from '../../context/AppMetadataContext';
import { CreateCaseDispatchContext, CreateCaseStateContext } from '../../context/CreateCaseContext';
import { ICreateCaseState, setCaseCreationDetails } from '../../reducers/CreateCaseReducer';
import CaseUtils from '../../utils/caseUtils';
import { Dropdown } from '../shared/input/DropdownList';

interface IProps extends IDClassNameProps { }
const defaultProps: Partial<IProps> = {
    id: '',
    className: ''
};

function SupportLevel(props: IProps) {
    const { createCaseState: {
        entitlement, severity
    } } = useContext(CreateCaseStateContext);
    const { appMetadataState: { allCaseEntitlements } } = useContext(AppMetadataStateContext);
    const createCaseDispatch = useContext(CreateCaseDispatchContext);

    const [isSupportLevelInValid, setIsSupportLevelInValid] = useState(false);

    const onCaseDetailsChange = (caseDetails: Partial<ICreateCaseState>) => {
        setCaseCreationDetails(createCaseDispatch, caseDetails);
    };

    const onEntitlementChange = (option: IOption<Partial<IStrataEntitlement>>) => {
        const casePayload: Partial<ICreateCaseState> = { entitlement: { sla: option.value.sla } };
        casePayload.fts = CaseUtils.showFts(option.value.sla, severity);
        validateSupportLevel(option);
        onCaseDetailsChange(casePayload);
    };
    const validateSupportLevel = (selectedItem: IOption<Partial<IStrataEntitlement>>): void => {
        const isInvalid = isEmpty(selectedItem) || isEmpty(selectedItem.label);
        setIsSupportLevelInValid(isInvalid);
    };

    const sla = get(entitlement, 'sla', '');
    const selectedSla = (isEmpty(sla) && !isEmpty(allCaseEntitlements.data)) ? allCaseEntitlements.data[0].sla : sla;
    if (sla !== selectedSla) { onCaseDetailsChange({ entitlement: { sla: selectedSla } }); }

    return (<div className={`form-group ${props.className}`} id={`${props.id}`}>
        <label htmlFor="open-case-support-level">Support Level {!isEmpty(allCaseEntitlements.data) && <span className="form-required">&#42;</span>}</label>
        <Popover aria-label="Support Level info" position={PopoverPosition.top}
            bodyContent={
                <p>Learn more about our <a href="/support/offerings/production/sla.html" target="_blank">production support service level agreement</a></p>
            }
            closeBtnAriaLabel="Close">
                <i aria-label="Support Level info" className="m-l-1 fa fa-question-circle" />
        </Popover>
        <Dropdown<Partial<IStrataEntitlement>>
            id="open-case-support-level"
            name="open-case-support-level"
            placeholder="Select"
            title={`Select Support Level`}
            list={allCaseEntitlements.data ? toOptions<Partial<IStrataEntitlement>>(allCaseEntitlements.data, 'sla') : []}
            selectedItem={toOption<Partial<IStrataEntitlement>>({ sla: selectedSla }, 'sla')}
            disabled={allCaseEntitlements.isError || isEmpty(allCaseEntitlements.data)}
            isLoadingList={allCaseEntitlements.isFetching}
            isInValid={isSupportLevelInValid}
            onChange={onEntitlementChange}
            onOuterClick={validateSupportLevel}
        />
        {isEmpty(allCaseEntitlements.data) && <p className="form-instructions">{allCaseEntitlements.isError ? 'Error loading Support Levels' : 'No active subscriptions'}</p>}
    </div>);
}
SupportLevel.defaultProps = defaultProps;
export default SupportLevel;
