import isEmpty from 'lodash/isEmpty';
import React, { useContext, useEffect, useState } from 'react';
import { Trans } from 'react-i18next';
import { AppMetadataStateContext } from '../../context/AppMetadataContext';
import { CreateCaseDispatchContext, CreateCaseStateContext } from '../../context/CreateCaseContext';
import { RouteContext, RouteDispatchContext } from '../../context/RouteContext';
import { getUpdatedDescription } from '../../reducers/CreateCaseHelpers';
import { ICreateCaseState, KtQuestionConstant, LargeDescriptionErrorMessage, setCaseCreationDetails } from '../../reducers/CreateCaseReducer';
import { AppRouteSections, RouteReducerConstants } from '../../reducers/RouteReducer';

interface IProps {}

export default function KtQuestions(props: IProps) {
    const { createCaseState: { issue, environment, periodicityOfIssue, timeFramesAndUrgency, hasLargeCaseDescription, description } } = useContext(CreateCaseStateContext);
    const createCaseDispatch = useContext(CreateCaseDispatchContext);
    const { routeState: { activeSection, isSectionValid } } = useContext(RouteContext);
    const dispatchToRouteReducer = useContext(RouteDispatchContext);

    const [isKTQ2TextAreaActive, setKTQ2TextAreaActive] = useState(false);
    const [isKTQ2InValid, setKTQ2InValid] = useState(false);
    const onKTQ2FocusChange = (e: React.FocusEvent<HTMLInputElement>) => {
        setKTQ2TextAreaActive(e.type === 'focus');
        e.type !== 'focus' && setKTQ2InValid(isEmpty(description));
    };

    const [isKTQ3TextAreaActive, setKTQ3TextAreaActive] = useState(false);
    const [isKTQ3InValid, setKTQ3InValid] = useState(false);
    const onKTQ3FocusChange = (e: React.FocusEvent<HTMLTextAreaElement>) => {
        setKTQ3TextAreaActive(e.type === 'focus');
        e.type !== 'focus' && setKTQ3InValid(isEmpty(description));
    };

    const [isKTQ4TextAreaActive, setKTQ4TextAreaActive] = useState(false);
    const [isKTQ4InValid, setKTQ4InValid] = useState(false);
    const onKTQ4FocusChange = (e: React.FocusEvent<HTMLInputElement>) => {
        setKTQ4TextAreaActive(e.type === 'focus');
        e.type !== 'focus' && setKTQ4InValid(isEmpty(description));
    };

    useEffect(() => {
        setKTQ2InValid(isEmpty(description));
        setKTQ3InValid(isEmpty(description));
        setKTQ4InValid(isEmpty(description));
    }, [description]);

    // nextButtonRef
    const {appMetadataState: {nextButtonRef}} = useContext(AppMetadataStateContext);

    useEffect(() => {
        if (activeSection !== AppRouteSections.IMPROVE_CASE) { return; }
        const isSectionValidLocal = !hasLargeCaseDescription;
        if (isSectionValid === isSectionValidLocal) { return; }
        dispatchToRouteReducer({ type: RouteReducerConstants.setIsSectionValid, payload: { isSectionValid: isSectionValidLocal } });
    }, [hasLargeCaseDescription, activeSection]);

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

    const onKtQ2Change = (e: React.ChangeEvent<HTMLInputElement>) => {
        onCaseDetailsChange({environment: e.target.value});
        const newDescription = getUpdatedDescription(issue, e.target.value, periodicityOfIssue, timeFramesAndUrgency);
        onCaseDetailsChange({ description: newDescription });
    };
    const onKtQ3Change = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        onCaseDetailsChange({periodicityOfIssue: e.target.value});
        const newDescription = getUpdatedDescription(issue, environment, e.target.value, timeFramesAndUrgency);
        onCaseDetailsChange({ description: newDescription });
    };
    const onKtQ4Change = (e: React.ChangeEvent<HTMLInputElement>) => {
        onCaseDetailsChange({timeFramesAndUrgency: e.target.value});
        const newDescription = getUpdatedDescription(issue, environment, periodicityOfIssue, e.target.value);
        onCaseDetailsChange({ description: newDescription });
    };
    const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        // simulating click
        nextButtonRef.current.click();
    };
    return (
        <form onSubmit={handleFormSubmit} className="push-top">
            <div className="form-group">
                <label htmlFor="ktQ2-environment"><Trans>{KtQuestionConstant.environment}</Trans> {
                    isEmpty(issue) && isEmpty(periodicityOfIssue) && isEmpty(timeFramesAndUrgency) && <span className="form-required">&#42;</span>
                }</label>
                <input
                    type="text"
                    className={`form-control${isKTQ2InValid || hasLargeCaseDescription ? ' form-invalid' : ''}`}
                    id="ktQ2-environment"
                    value={environment}
                    disabled={isEmpty(environment) && hasLargeCaseDescription && !isKTQ2TextAreaActive}
                    onChange={onKtQ2Change}
                    onFocus={onKTQ2FocusChange}
                    onBlur={onKTQ2FocusChange}
                    aria-required={isEmpty(issue) && isEmpty(periodicityOfIssue) && isEmpty(timeFramesAndUrgency)}
                    />
                <p className="form-instructions">{`${hasLargeCaseDescription && isKTQ2TextAreaActive ? LargeDescriptionErrorMessage : ''}`}</p>
            </div>
            <div className="form-group">
                <label htmlFor="ktQ3-periodicityOfIssue"><Trans>{KtQuestionConstant.periodicityOfIssue}</Trans> {
                    isEmpty(issue) && isEmpty(environment) && isEmpty(timeFramesAndUrgency) && <span className="form-required">&#42;</span>
                }</label>
                <textarea
                    className={`form-control${isKTQ3InValid || hasLargeCaseDescription ? ' form-invalid' : ''}`}
                    id="ktQ3-periodicityOfIssue"
                    value={periodicityOfIssue}
                    disabled={isEmpty(periodicityOfIssue) && hasLargeCaseDescription && !isKTQ3TextAreaActive}
                    onChange={onKtQ3Change}
                    onFocus={onKTQ3FocusChange}
                    onBlur={onKTQ3FocusChange}
                    aria-required={isEmpty(issue) && isEmpty(environment) && isEmpty(timeFramesAndUrgency)}
                    />
                <p className="form-instructions">{`${hasLargeCaseDescription && isKTQ3TextAreaActive ? LargeDescriptionErrorMessage : ''}`}</p>
            </div>
            <div className="form-group">
                <label htmlFor="ktQ4-timeFramesAndUrgency">{KtQuestionConstant.timeFramesAndUrgency} {
                    isEmpty(issue) && isEmpty(environment) && isEmpty(periodicityOfIssue) && <span className="form-required">&#42;</span>
                }</label>
                <input
                    type="text"
                    className={`form-control${isKTQ4InValid || hasLargeCaseDescription ? ' form-invalid' : ''}`}
                    id="ktQ4-timeFramesAndUrgency"
                    value={timeFramesAndUrgency}
                    disabled={isEmpty(timeFramesAndUrgency) && hasLargeCaseDescription && !isKTQ4TextAreaActive}
                    onChange={onKtQ4Change}
                    onFocus={onKTQ4FocusChange}
                    onBlur={onKTQ4FocusChange}
                    aria-required={isEmpty(issue) && isEmpty(environment) && isEmpty(periodicityOfIssue)}
                    />
                <p className="form-instructions">{`${hasLargeCaseDescription && isKTQ4TextAreaActive ? LargeDescriptionErrorMessage : ''}`}</p>
            </div>
        </form>
    );
}
