import { faPaperclip } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import classNames from 'classnames';
import React, { useContext } from 'react';
import { useSelector } from 'react-redux';
import { findChildElement, getAttribute, query, queryAncestors, useIsElementInViewport } from '../../dom-utils';
import { useExamTranslation } from '../../i18n';
import { url } from '../../url';
import { CommonExamContext } from '../context/CommonExamContext';
import { QuestionContext } from '../context/QuestionContext';
import { Indicator } from './AnswerIndicator';
import { IsInSidebarContext } from '../context/IsInSidebarContext';
export const TOCQuestion = ({ element, renderChildNodes }) => {
    var _a;
    const { attachmentsURL } = useContext(CommonExamContext);
    const { displayNumber, maxScore, level } = useContext(QuestionContext);
    const { t } = useExamTranslation();
    const showAttachmentLinks = true;
    const { isInSidebar } = useContext(IsInSidebarContext);
    const questionTitle = findChildElement(element, 'question-title');
    const externalMaterial = showAttachmentLinks && displayNumber != null && query(element, 'external-material');
    const subquestions = [];
    let answersById = {};
    let hasQuestionValidationError = false;
    if (isInSidebar) {
        const answers = useSelector((state) => state.answers);
        answersById = (answers === null || answers === void 0 ? void 0 : answers.answersById) || {};
        const subquestionNodes = element.querySelectorAll('[question-id]');
        const questionValidationErrors = (_a = answers.validationErrors) === null || _a === void 0 ? void 0 : _a.filter(i => (i === null || i === void 0 ? void 0 : i.elementType) === 'question');
        hasQuestionValidationError = !!(questionValidationErrors === null || questionValidationErrors === void 0 ? void 0 : questionValidationErrors.find(i => i.displayNumber === displayNumber));
        subquestionNodes.forEach(e => {
            var _a;
            const id = Number(e.getAttribute('question-id'));
            const type = e.getAttribute('type') || '';
            const subQuestionDisplayNumber = e.getAttribute('display-number') || '';
            const hasError = !!(questionValidationErrors === null || questionValidationErrors === void 0 ? void 0 : questionValidationErrors.find(i => i.displayNumber === subQuestionDisplayNumber));
            const childQuestionHasError = questionValidationErrors
                .flatMap(i => ('childQuestions' in i ? i.childQuestions : []))
                .includes(subQuestionDisplayNumber);
            const hasAnswer = !!((_a = answersById[id]) === null || _a === void 0 ? void 0 : _a.value);
            if (id) {
                subquestions.push({
                    id,
                    type,
                    error: hasError || (childQuestionHasError && hasAnswer),
                    displayNumber: subQuestionDisplayNumber
                });
            }
        });
    }
    const subQuestionError = !!subquestions.find(i => i.error);
    const subquestionsAnswered = subquestions === null || subquestions === void 0 ? void 0 : subquestions.filter(i => { var _a; return (_a = answersById[i.id]) === null || _a === void 0 ? void 0 : _a.value; }).length;
    const maxAnswers = Number(element.getAttribute('max-answers'));
    const requiredAnswers = maxAnswers || subquestions.length;
    const isVisible = useIsElementInViewport('question', displayNumber);
    return (React.createElement("li", { "data-list-number": `${displayNumber}.`, onClick: () => (isInSidebar ? (window.location.href = `#question-nr-${displayNumber}`) : undefined), className: classNames(`level-${level}`, { error: hasQuestionValidationError, current: isVisible }) },
        React.createElement("span", { className: "e-column e-question-title" },
            React.createElement("a", { href: url('', { hash: `question-nr-${displayNumber}` }), tabIndex: isInSidebar ? -1 : undefined },
                React.createElement("span", null, renderChildNodes(questionTitle)))),
        isInSidebar && (React.createElement("div", { className: classNames('numeric-answer-indicator', {
                error: subQuestionError,
                ok: subquestionsAnswered === requiredAnswers
            }) },
            subquestionsAnswered,
            "/",
            requiredAnswers)),
        !isInSidebar && externalMaterial && (React.createElement("span", { className: "e-column e-column--narrow e-external-material" },
            React.createElement("a", { href: url(attachmentsURL, {
                    hash: getAttribute(queryAncestors(externalMaterial, 'question'), 'display-number')
                }), target: "attachments" }, t('material')))),
        React.createElement("span", { className: "e-column e-column--narrow table-of-contents--score-column" }, t('points', { count: maxScore })),
        isInSidebar && (React.createElement("span", { className: "e-column e-column--narrow e-external-material" }, externalMaterial && React.createElement(FontAwesomeIcon, { size: "sm", icon: faPaperclip, fixedWidth: true }))),
        React.createElement("div", { className: "answers" },
            subquestions.map(i => (React.createElement(Indicator, { key: i.id, type: i.type, id: i.id, answer: answersById[i.id], error: i.error, displayNumber: i.displayNumber }))),
            ' ')));
};
//# sourceMappingURL=TOCQuestion.js.map