import isEmpty from 'lodash/isEmpty';
import React, { useContext, useMemo, useState } from 'react';
import { CreateCaseDispatchContext, CreateCaseStateContext } from '../../context/CreateCaseContext';
import { ICreateCaseState, setCaseCreationDetails } from '../../reducers/CreateCaseReducer';

interface IProps { }

export default function OpenCaseIssue(props: IProps) {
    const { createCaseState: { summary } } = useContext(CreateCaseStateContext);
    const createCaseDispatch = useContext(CreateCaseDispatchContext);
    const [isSummaryInValid, setIsSummaryInValid] = useState(false);

    const onSummaryBlur = (e: React.FocusEvent<HTMLInputElement>) => {
        setIsSummaryInValid(isEmpty(e.target.value));
    };

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

    const onSummaryChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        onCaseDetailsChange({ summary: e.target.value });
        setIsSummaryInValid(isEmpty(e.target.value));
    };

    return useMemo(() => {
        return (<div className="form-group">
            <label htmlFor="open-case-summary">Issue Statement <span className="form-required">&#42;</span></label>
            <input
                type="text"
                id="open-case-summary"
                className={`form-control${isSummaryInValid ? ' form-invalid' : ''}`}
                aria-invalid={isSummaryInValid}
                aria-required={true}
                name="open-case-summary"
                value={summary}
                onChange={onSummaryChange}
                onBlur={onSummaryBlur}
            />
        </div>);
    }, [props, summary, isSummaryInValid]);
}
