
import { IOption } from '@rh-support/types';
import map from 'lodash/map';
import React, { useContext} from 'react';
import { AppMetadataStateContext } from '../../context/AppMetadataContext';
import { CreateCaseDispatchContext, CreateCaseStateContext } from '../../context/CreateCaseContext';
import { ICreateCaseState, setCaseCreationDetails } from '../../reducers/CreateCaseReducer';
import Constants from '../shared/Constants';
import { Dropdown } from '../shared/input/DropdownList';

export interface IProps {}

export default function CaseLanguageSelector(props: IProps) {
    const { createCaseState } = useContext(CreateCaseStateContext);
    const { language } = createCaseState;
    const { appMetadataState: { caseLanguages } } = useContext(AppMetadataStateContext);
    const createCaseDispatch = useContext(CreateCaseDispatchContext);

    const onCaseDetailsChange = (caseDetails: Partial<ICreateCaseState>) => {
        setCaseCreationDetails(createCaseDispatch, caseDetails);
    };
    const onLanguageChange = (selection: IOption<string>) => {
        onCaseDetailsChange({ language: selection.value });
    };
    const languagesList: Array<IOption<string>> = map(caseLanguages.data, (cl) => ({label: Constants.languagesMap[cl] || cl, value: cl}));
    const selectedLanguage: IOption<string> = {label: Constants.languagesMap[language] || language, value: language};
    return (<div className="form-group">
        <label htmlFor="open-case-language">Case Language</label>
        <Dropdown<string>
            id="open-case-language"
            name="open-case-language"
            placeholder="Select"
            title={`Select Case Language`}
            list={languagesList}
            selectedItem={selectedLanguage}
            disabled={caseLanguages.isError}
            isLoadingList={caseLanguages.isFetching}
            onChange={onLanguageChange}
            isInValid={caseLanguages.isError}
        />
        <p className="form-instructions">Please choose a language for your case communication with our support engineers.</p>
    </div>);
}
