import { sendTrackingData } from '@rh-support/api';
import find from 'lodash/find';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import React, { useContext, useEffect } from 'react';
import { RouteComponentProps } from 'react-router';
import { AppMetadataStateContext } from '../../context/AppMetadataContext';
import { CreateCaseDispatchContext, CreateCaseStateContext } from '../../context/CreateCaseContext';
import { RouteContext, RouteDispatchContext } from '../../context/RouteContext';
import { getIrtForSLAAndSeverity } from '../../reducers/CreateCaseHelpers';
import { CreateCaseReducerConstants } from '../../reducers/CreateCaseReducer';
import { AppRouteSections, IRouteUrlParams, RouteReducerConstants } from '../../reducers/RouteReducer';
import RouteUtils from '../../utils/routeUtils';
import AlertMessage, { AlertType } from '../shared/AlertMessage';
import { AttachmentDispatchContext, AttachmentStateContext } from '../shared/fileUpload/AttachmentReducerContext';
import FileUploader from '../shared/fileUpload/FileUploader';
import { resetAttachment } from '../shared/fileUpload/reducer/AttachemntReducer';

interface IProps {
    routeProps: RouteComponentProps<IRouteUrlParams>;
}

export default function SubmitCase(props: IProps) {
    const { createCaseState } = useContext(CreateCaseStateContext);
    const { routeState: { appRouteSectionsSequence } } = useContext(RouteContext);
    const { attachmentState } = useContext(AttachmentStateContext);
    const createCaseDispatch = useContext(CreateCaseDispatchContext);
    const dispatchToAttachmentReducer = useContext(AttachmentDispatchContext);
    const isUploadingAttachment = !isEmpty(find(attachmentState.caseFiles.selectedLocalFiles, (localFile) => localFile.uploadProgress.inProgress || localFile.uploadProgress.verifying));
    const dispatchToRouteReducer = useContext(RouteDispatchContext);
    const { appMetadataState: { guid }  } = useContext(AppMetadataStateContext);

    useEffect(() => {
        if (isEmpty(createCaseState.caseNumber) || isEmpty(guid.data)) { return; }
        sendTrackingData('case_number', [createCaseState.caseNumber], guid.data);
    }, [createCaseState.caseNumber, guid.data]);

    const onCaseOpen = (e) => {
        window.open(getCaseURL());
    };
    const getCaseURL = () => {
        return `/support/cases/#/case/${createCaseState.caseNumber}`;
    };
    const getSlaURL = () => {
        return '/support/offerings/production/sla';
    };
    const onNew = (e: React.MouseEvent<HTMLButtonElement>) => {
        resetAttachment(dispatchToAttachmentReducer);
        createCaseDispatch({ type: CreateCaseReducerConstants.resetAppState });
        dispatchToRouteReducer({ type: RouteReducerConstants.updateSectionsToHide, payload: { sectionsToHide: [] } });
        RouteUtils.navigateToSection(props.routeProps, AppRouteSections.PRODUCT_SELECTOR, appRouteSectionsSequence, true);
    };
    const irt = getIrtForSLAAndSeverity(get(createCaseState, 'entitlement.sla', ''), createCaseState.severity);
    return (<>
        <AlertMessage className="push-top" message="Failed to add user." type={AlertType.DANGER} show={createCaseState.addNotifiedUserError} />
        <AlertMessage className="push-top" type={AlertType.DANGER} show={createCaseState.caseCreationError}
            message={`${isEmpty(createCaseState.caseCreationErrorMessage) ? 'Failed to create your case' : createCaseState.caseCreationErrorMessage}`} />
        {!createCaseState.isCreatingCase && !createCaseState.caseCreationError && <>
            <p className="kicker kicker-sm">
                <a href={getCaseURL()} target="_blank">Case #{createCaseState.caseNumber}</a> successfully created.
            </p>
            <p>
                Thank you for contacting Red Hat support!<br />
                {!isEmpty(irt) && <>You should receive a response within <strong>{irt}</strong>.
                &nbsp;<a href={getSlaURL()} className="inline-link" target="_blank">SLA information</a></>}
            </p>
            <p>
                <button className="btn btn-app btn-primary" onClick={onCaseOpen}>View your case</button>
                <button disabled={isUploadingAttachment || createCaseState.isCreatingCase} onClick={onNew} className="btn btn-app btn-open-white btn-inline">
                    Troubleshoot a new issue
                </button>
            </p>
            {!isEmpty(attachmentState.caseFiles.selectedLocalFiles)  && <FileUploader caseNumber={createCaseState.caseNumber}  />}
        </>}
    </>);
}
