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

interface IProps {}

export default function Description(props: IProps) {
    const { createCaseState: { issue, environment, periodicityOfIssue, timeFramesAndUrgency, hasLargeCaseDescription, description } } = useContext(CreateCaseStateContext);
    const createCaseDispatch = useContext(CreateCaseDispatchContext);
    const [isKTQ1IssueInValid, setKTQ1IssueInValid] = useState(false);
    useEffect(() => {
        hasFocusedOut && setKTQ1IssueInValid(isEmpty(description));
    }, [description]);
    const [hasFocusedOut, setHasFocusedOut] = useState(false);
    const [isIssueTextAreaActive, setIssueTextAreaActive] = useState(false);
    const onKTQ1IssueFocusChange = (e: React.FocusEvent<HTMLTextAreaElement>) => {
        setIssueTextAreaActive(e.type === 'focus');
        e.type === 'blur' && setHasFocusedOut(true);
        e.type === 'blur' && setKTQ1IssueInValid(isEmpty(description));
    };

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

    const onKTQ1IssueChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        const newDescription = getUpdatedDescription(e.target.value, environment, periodicityOfIssue, timeFramesAndUrgency);
        onCaseDetailsChange({issue: e.target.value, description: newDescription});
    };

    return (<div className="form-group">
        <label htmlFor="open-case-ktQ1-issue">Case Details {
            isEmpty(environment) && isEmpty(periodicityOfIssue) && isEmpty(timeFramesAndUrgency) && <span className="form-required">&#42;</span>
        }</label>
        <textarea
            id="open-case-ktQ1-issue"
            name="open-case-ktQ1-issue"
            className={`form-control${isKTQ1IssueInValid || hasLargeCaseDescription ? ' form-invalid' : ''}`}
            aria-invalid={isKTQ1IssueInValid}
            aria-required={isEmpty(environment) && isEmpty(periodicityOfIssue) && isEmpty(timeFramesAndUrgency)}
            value={issue}
            disabled={isEmpty(issue) && hasLargeCaseDescription && !isIssueTextAreaActive}
            onChange={onKTQ1IssueChange}
            onFocus={onKTQ1IssueFocusChange}
            onBlur={onKTQ1IssueFocusChange}
        />
        <p className="form-instructions">{`${(hasLargeCaseDescription && isIssueTextAreaActive) ? LargeDescriptionErrorMessage : ''}`}</p>
    </div>);
}
