import { IEdmundAbbottBodyV2, sendTrackingData } from '@rh-support/api';
import map from 'lodash/map';
import React, { useContext, useEffect, useRef } from 'react';
import { AppMetadataStateContext } from '../../context/AppMetadataContext';
import { CreateCaseDispatchContext, CreateCaseStateContext } from '../../context/CreateCaseContext';
import { RecommendationDispatchContext, RecommendationStateContext } from '../../context/RecommendationContext';
import { RouteContext, RouteDispatchContext } from '../../context/RouteContext';
import { RulesDispatchContext } from '../../context/RulesContext';
import { getDescriptionWOQues } from '../../reducers/CreateCaseHelpers';
import { setCaseRecommendations } from '../../reducers/CreateCaseReducer';
import { fetchRecommendations, setCurrentPage, setVisibleDocs } from '../../reducers/RecommendationsReducer';
import { AppRouteSections, RouteReducerConstants } from '../../reducers/RouteReducer';
import { fetchEdmundAbbottRules } from '../../reducers/RulesReducer';
import CaseUtils from '../../utils/caseUtils';
import AlertMessage, { AlertType } from '../shared/AlertMessage';
import LoadingIndicator from '../shared/LoadingIndicator';
import Pagination from './Pagination';
import ResultRow from './ResultRow';

interface IProps {}

export default function Results(props: IProps) {
    const { createCaseState: { product, version, issue, environment, periodicityOfIssue, timeFramesAndUrgency, summary , recommendations} } = useContext(CreateCaseStateContext);
    const dispatchCreateCaseReducer = useContext(CreateCaseDispatchContext);
    const { routeState: { activeSection, isSectionValid } } = useContext(RouteContext);
    const dispatchToRouteReducer = useContext(RouteDispatchContext);
    const rulesDispatch = useContext(RulesDispatchContext);
    const { appMetadataState } = useContext(AppMetadataStateContext);
    const { guid, loggedInUsersAccount, loggedInUser } = appMetadataState;
    const resultRowRef = useRef(null);
    // internal state
    // const [recommendationState, recommendationDispatch] = useReducer(recommandationsReducer, initialRecommendationsState);
    // using context
    const {recommendationState} = useContext(RecommendationStateContext);
    const recommendationDispatch = useContext(RecommendationDispatchContext);

    const PAGESIZE = 5;
    const MAXROW = 25;

    useEffect(() => {
        if (activeSection !== AppRouteSections.RESULTS) { return; }
        if (window.sessionjs.isAuthenticated()) {
            doSearch(window.sessionjs);
        }
    }, [product, version, issue, environment, periodicityOfIssue, timeFramesAndUrgency, summary, activeSection]);

    useEffect(() => {
        if (recommendationState.visibleDocs.length !== 0) {
            setCaseRecommendations(dispatchCreateCaseReducer, recommendationState.visibleDocs, recommendations);

            // send result to tracking api
            const result: string[] = [];
            recommendationState.visibleDocs.forEach((item) => {
              result.push(item.view_uri);
            });
            sendTrackingData('issue_results', result, guid.data);
        }
    }, [recommendationState.visibleDocs]);

    // Validations effect
    useEffect(() => {
        if (activeSection !== AppRouteSections.RESULTS) { return; }
        const isSectionValidLocal = !recommendationState.isLoadingRecommendations;
        if (isSectionValid === isSectionValidLocal) { return; }
        dispatchToRouteReducer({ type: RouteReducerConstants.setIsSectionValid, payload: { isSectionValid: isSectionValidLocal } });
    }, [recommendationState.isLoadingRecommendations]);

    const doSearch = async (session) => {
        if (activeSection !== AppRouteSections.RESULTS) { return; }
        fetchRecommendations(recommendationDispatch, { product, version, description: getDescriptionWOQues(issue, environment, periodicityOfIssue, timeFramesAndUrgency), summary }, MAXROW, PAGESIZE);
        // call EA Ruls Api to get new rules
        const rulesBody: IEdmundAbbottBodyV2 = {
            caseType: {
                product, version, summary, description: getDescriptionWOQues(issue, environment, periodicityOfIssue, timeFramesAndUrgency),
                accountNumber: session.getUserInfo().account_number,
                owner: null,
                language: null,
                caseNumber: null
            },
            accountType: { isSecure: loggedInUsersAccount.data.is_secure || false },
            userType: { canAddAttachments: loggedInUser.data.can_add_attachments || false },
            fields: ['title', 'cta', 'description', 'rule_type', 'rule_sub_type']
        };
        fetchEdmundAbbottRules(rulesDispatch, rulesBody);
    };

    const pageChanged = (p: number) => {
        const oldP = recommendationState.currentPage;
        setCurrentPage(recommendationDispatch, p);
        if (p && p !== oldP) {
            window.setTimeout(() => {
                CaseUtils.scrollIntoSection(resultRowRef);
                const visDocs = recommendationState.allDocs.slice((p - 1) * PAGESIZE, (p - 1) * PAGESIZE + PAGESIZE);
                setVisibleDocs(recommendationDispatch, visDocs);
            }, 0);
        }
    };
    return (<>
        <LoadingIndicator show={recommendationState.isLoadingRecommendations} size="lg" />
        <AlertMessage type={AlertType.DANGER} className="push-top" message="There was an error loading solutions." show={recommendationState.isLoadingRecommendationsError} />
        {!recommendationState.isLoadingRecommendations && !recommendationState.isLoadingRecommendationsError &&
            <div ref={resultRowRef}>
                {map(recommendationState.visibleDocs, (doc, i) => <ResultRow guid={guid.data} doc={doc} key={doc.view_uri} index={i}/>)}
                <Pagination show={recommendationState.numFound !== 0 && recommendationState.numFound > PAGESIZE}
                    pageSize={PAGESIZE}
                    p={recommendationState.currentPage}
                    numFound={MAXROW}
                    onUpdate={pageChanged} />
            </div>
        }
    </>);
}
