import find from 'lodash/find';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import map from 'lodash/map';
import React, { useContext, useEffect, useRef } from 'react';
import { RouteComponentProps } from 'react-router';
import { AttachmentStateContext } from '../shared/fileUpload/AttachmentReducerContext';
import { AppMetadataStateContext } from '../../context/AppMetadataContext';
import { CreateCaseStateContext } from '../../context/CreateCaseContext';
import { RouteContext, RouteDispatchContext } from '../../context/RouteContext';
import { isCaseStateValid } from '../../reducers/CreateCaseHelpers';
import { AppRouteSections, IRouteUrlParams, RouteReducerConstants } from '../../reducers/RouteReducer';
import CaseUtils from '../../utils/caseUtils';
import RouteUtils from '../../utils/routeUtils';
import Constants from '../shared/Constants';
import ReviewItem from './ReviewItems';

interface IProps {
    routeProps: RouteComponentProps<IRouteUrlParams>;
}
export default function Review(props: IProps) {
    const {createCaseState} = useContext(CreateCaseStateContext);
    const {attachmentState} = useContext(AttachmentStateContext);
    const { appMetadataState: {loggedInUsersAccount, caseGroups, loggedInUserJwtToken} } = useContext(AppMetadataStateContext);
    const { routeState: { activeSection, isSectionValid, appRouteSectionsSequence } } = useContext(RouteContext);
    const dispatchToRouteReducer = useContext(RouteDispatchContext);

    // creating case description ref
    const caseDescriptionRef: React.MutableRefObject<HTMLPreElement> = useRef(null);

    useEffect(() => {
        if (activeSection !== AppRouteSections.REVIEW) { return; }
        const isSectionValidLocal = isCaseStateValid(createCaseState, loggedInUsersAccount.data.require_cgroup_on_create, loggedInUserJwtToken);
        if (isSectionValid === isSectionValidLocal) { return; }
        dispatchToRouteReducer({ type: RouteReducerConstants.setIsSectionValid, payload: { isSectionValid: isSectionValidLocal } });
    }, [createCaseState, activeSection, loggedInUsersAccount.data]);

    const getNotifiedUsers = (): string[] => {
        const notifiedUser: string[] = [];
        map(createCaseState.selectedNotificationContacts, (user) => {
            notifiedUser.push(`${user.firstName} ${user.lastName} (${user.ssoUsername})`);
        });
        return notifiedUser;
    };
    const render24X7Components = () => {
        if (CaseUtils.showFts(get(createCaseState, 'entitlement.sla', ''), createCaseState.severity)) {
            return (
                <>
                    <ReviewItem
                        linkTo={
                            RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.OPEN_CASE, appRouteSectionsSequence)
                        }
                        label="24x7 Support"
                    >
                        <p>{createCaseState.fts ? 'true' : 'false'}</p>
                    </ReviewItem>
                    {createCaseState.fts && createCaseState.contactInfo24X7 &&
                         <ReviewItem
                            linkTo={
                                RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.OPEN_CASE, appRouteSectionsSequence)
                            }
                            label="24x7 Contact"
                        >
                            <p>{createCaseState.contactInfo24X7}</p>
                        </ReviewItem>
                    }
                </>
            );
        }
    };

    const getAttachmentList = (): string[] => {
        const attachmentFiles: string[] = [];
        map(attachmentState.caseFiles.selectedLocalFiles, (file) => {
            attachmentFiles.push(file.name);
        });
        return attachmentFiles;
    };
    const sla = get(createCaseState, 'entitlement.sla', '');

    return (<>
        <div className="card card-light card-md">
            <ul className="list-flat">
            <ReviewItem
                linkTo={
                    RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.PRODUCT_SELECTOR, appRouteSectionsSequence)
                }
                label="Environment"
            >
                <p>{`${createCaseState.product} ${createCaseState.version}`}</p>
            </ReviewItem>
            <ReviewItem
                linkTo={
                    RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.OPEN_CASE, appRouteSectionsSequence)
                }
                label="Issue statement"
            >
                <p>{createCaseState.summary}</p>
            </ReviewItem>
            <ReviewItem
                linkTo={
                    RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.OPEN_CASE, appRouteSectionsSequence)
                }
                label="Case details"
                moreLessRef={caseDescriptionRef}
            >
                <pre ref={caseDescriptionRef}>{createCaseState.issue}</pre>
            </ReviewItem>
            <ReviewItem
                linkTo={
                    RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.OPEN_CASE, appRouteSectionsSequence)
                }
                label="Case type"
            >
                <p>{createCaseState.type}</p>
            </ReviewItem>
            <ReviewItem
                linkTo={
                    RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.OPEN_CASE, appRouteSectionsSequence)
                }
                label="Severity level"
            >
                <p>{`${!isEmpty(sla) ?  sla + ' / ' : ''}${createCaseState.severity}`}</p>
            </ReviewItem>
            {render24X7Components()}
            {loggedInUsersAccount.data.has_enhanced_sla &&
                <ReviewItem
                    linkTo={RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.OPEN_CASE, appRouteSectionsSequence)}
                    label="Enhanced SLA"
                >
                    <p>{createCaseState.enhancedSLA ? 'true' : 'false'}</p>
                </ReviewItem>
            }
            {loggedInUsersAccount.data.require_cgroup_on_create &&
                <ReviewItem
                    linkTo={RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.OPEN_CASE, appRouteSectionsSequence)}
                    label="Case Group"
                >
                    <p>{find(caseGroups.data, (g) => g.number === createCaseState.folderNumber).name}</p>
                </ReviewItem>
            }
            {attachmentState.caseFiles.selectedLocalFiles.length > 0 &&
                <ReviewItem
                    linkTo={
                        RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.IMPROVE_CASE, appRouteSectionsSequence)
                    }
                    label="File upload"
                >
                    <p>{getAttachmentList().join(', ')}</p>
                </ReviewItem>
            }
            {createCaseState.environment &&
                <ReviewItem
                    linkTo={
                        RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.IMPROVE_CASE, appRouteSectionsSequence)
                    }
                    label="Environment"
                >
                    <p>{createCaseState.environment}</p>
                </ReviewItem>
            }
            {createCaseState.periodicityOfIssue &&
                <ReviewItem
                    linkTo={
                        RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.IMPROVE_CASE, appRouteSectionsSequence)
                    }
                    label="Frequency of the issue"
                >
                    <p>{createCaseState.periodicityOfIssue}</p>
                </ReviewItem>
            }
            {createCaseState.timeFramesAndUrgency &&
                <ReviewItem
                    linkTo={
                        RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.IMPROVE_CASE, appRouteSectionsSequence)
                    }
                    label="Timeframe and business impact"
                >
                    <p>{createCaseState.timeFramesAndUrgency}</p>
                </ReviewItem>
            }
            {createCaseState.notifiedUsers.user.length > 0 &&
                <ReviewItem
                    linkTo={
                        RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.CASE_MGM, appRouteSectionsSequence)
                    }
                    label="Send notifications"
                >
                    <p>{getNotifiedUsers().join(', ')}</p>
                </ReviewItem>
            }
            {createCaseState.language &&
                <ReviewItem
                    linkTo={
                        RouteUtils.getNavigateToSectionLink(props.routeProps, AppRouteSections.CASE_MGM, appRouteSectionsSequence)
                    }
                    label="Case language"
                >
                    <p>{Constants.languagesMap[createCaseState.language]}</p>
                </ReviewItem>
            }
        </ul>
        </div>
    </>);
}
