import { IStrataMetadataValue } from '@rh-support/api';
import { IOption } from '@rh-support/types';
import isEmpty from 'lodash/isEmpty';
import React, { useContext, useMemo, useState } from 'react';
import { AppMetadataStateContext } from '../../context/AppMetadataContext';
import { CreateCaseDispatchContext, CreateCaseStateContext } from '../../context/CreateCaseContext';
import { ICreateCaseState, setCaseCreationDetails } from '../../reducers/CreateCaseReducer';
import { Dropdown } from '../shared/input/DropdownList';
import { toOption, toOptions } from '../shared/utils';

interface IProps { }

export default function CaseType(props: IProps) {
    const [isCaseTypeInValid, setIsCaseTypeInValid] = useState(false);
    const { createCaseState: { type } } = useContext(CreateCaseStateContext);
    const { appMetadataState: { allCaseTypes } } = useContext(AppMetadataStateContext);
    const createCaseDispatch = useContext(CreateCaseDispatchContext);

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

    const onCaseTypeChange = (option: IOption<IStrataMetadataValue>) => {
        onCaseDetailsChange({ type: option.value.name });
        validateCaseType(option);
    };
    const validateCaseType = (selectedItem: IOption<IStrataMetadataValue>): void => {
        setIsCaseTypeInValid(isEmpty(selectedItem) || isEmpty(selectedItem.label));
    };

    return useMemo(() => {
        return (<div className="form-group">
            <label htmlFor="open-case-type">Case Type <span className="form-required">&#42;</span></label>
            <Dropdown<IStrataMetadataValue>
                id="open-case-type"
                name="open-case-type"
                placeholder="Select"
                title={`Select Case Type`}
                list={allCaseTypes.data ? toOptions<IStrataMetadataValue>(allCaseTypes.data, 'name') : []}
                selectedItem={toOption<IStrataMetadataValue>({ name: type }, 'name')}
                disabled={allCaseTypes.isError}
                isLoadingList={allCaseTypes.isFetching}
                isInValid={isCaseTypeInValid}
                onChange={onCaseTypeChange}
                onOuterClick={validateCaseType}
            />
        </div>);
    }, [props, type, allCaseTypes, isCaseTypeInValid]);
}
