// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// Permit `any` in this file to handle the overloaded issue type. Todo: refactor CallSurvey to have PartialDeep<_CallSurvey> instead of any
// for tracking incomplete survey responses.
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Text, useTheme, Stack, Checkbox, Pivot, PivotItem, TextField } from '@fluentui/react';
import { _getKeys } from "../../../../../acs-ui-common/src";
import { checkboxClassName, questionTextStyle, helperTextStyle, freeFormTextFieldClassName, freeFormTextCheckboxStyles } from './TagsSurvey.styles';
/**
 * A component to allow users to send numerical ratings regarding call quality
 *
 * @internal
 */
export const _TagsSurvey = (props) => {
    const { callIssuesToTag, categoryHeadings, onConfirm, strings, showFreeFormTextField } = props;
    const [selectedTags, setSelectedTags] = useState({});
    const [textResponse, setTextResponse] = useState({});
    const [selectedTextResponse, setSelectedTextResponse] = useState({});
    const [checkedTextFields, setCheckedTextFields] = useState([]);
    const tags = useMemo(() => {
        const tags = {
            overallRating: [],
            audioRating: [],
            videoRating: [],
            screenshareRating: []
        };
        _getKeys(callIssuesToTag).forEach(issueCategory => {
            _getKeys(callIssuesToTag[issueCategory]).map(issue => {
                const issueCapitalized = (issue === null || issue === void 0 ? void 0 : issue.charAt(0).toUpperCase()) + (issue === null || issue === void 0 ? void 0 : issue.slice(1));
                const issueMessages = callIssuesToTag[issueCategory];
                if (tags[issueCategory]) {
                    tags[issueCategory].push({
                        message: issueMessages[issue],
                        issue: issueCapitalized
                    });
                }
                else {
                    tags[issueCategory] = [{
                            message: issueMessages[issue],
                            issue: issueCapitalized
                        }];
                }
            });
        });
        return tags;
    }, [callIssuesToTag]);
    const onChange = React.useCallback((issueCategory, checked, issue) => {
        if (checked) {
            if (issue) {
                setSelectedTags(prevState => {
                    const category = prevState === null || prevState === void 0 ? void 0 : prevState[issueCategory];
                    if (category && category.issues) {
                        category.issues = [category.issues, issue];
                    }
                    else {
                        prevState[issueCategory] = {
                            issues: [issue]
                        };
                    }
                    return prevState;
                });
            }
            else {
                setCheckedTextFields([...checkedTextFields, issueCategory]);
                setSelectedTextResponse(prevState => {
                    prevState[issueCategory] = textResponse[issueCategory];
                    return prevState;
                });
            }
        }
        else {
            if (issue) {
                setSelectedTags(prevState => {
                    var _a, _b;
                    // 'prevState[issueCategory]?.issues as ...' typing is required here to avoid a typescript limitation
                    // "This expression is not callable" caused by filter().
                    // More information can be found here: https://github.com/microsoft/TypeScript/issues/44373
                    const categoryIssues = (_b = (_a = prevState[issueCategory]) === null || _a === void 0 ? void 0 : _a.issues) === null || _b === void 0 ? void 0 : _b.filter((value) => value !== issue);
                    return Object.assign(Object.assign({}, prevState), { [issueCategory]: Object.assign(Object.assign({}, (prevState[issueCategory] || {})), { issues: categoryIssues }) });
                });
            }
            else {
                setCheckedTextFields(checkedTextFields.filter(id => id !== issueCategory));
                setSelectedTextResponse(prevState => {
                    delete prevState[issueCategory];
                    return prevState;
                });
            }
        }
    }, [textResponse, checkedTextFields]);
    const theme = useTheme();
    const onRenderLabel = useCallback((issueCategory) => {
        return React.createElement(TextField, { key: issueCategory, className: freeFormTextFieldClassName, underlined: true, placeholder: strings === null || strings === void 0 ? void 0 : strings.tagsSurveyTextFieldDefaultText, onChange: (e, v) => {
                if (v) {
                    setCheckedTextFields([...checkedTextFields, issueCategory]);
                    setTextResponse(prevState => {
                        prevState[issueCategory] = v;
                        return prevState;
                    });
                    setSelectedTextResponse(prevState => {
                        prevState[issueCategory] = v;
                        return prevState;
                    });
                }
            } });
    }, [strings === null || strings === void 0 ? void 0 : strings.tagsSurveyTextFieldDefaultText, checkedTextFields]);
    useEffect(() => {
        if (onConfirm) {
            onConfirm(selectedTags, selectedTextResponse);
        }
    }, [selectedTags, selectedTextResponse, onConfirm]);
    return React.createElement(React.Fragment, null,
        React.createElement(Stack, { verticalAlign: "center" },
            React.createElement(Text, { className: questionTextStyle(theme) }, strings === null || strings === void 0 ? void 0 : strings.tagsSurveyQuestion)),
        React.createElement(Pivot, null, _getKeys(tags).map((key, i) => {
            return React.createElement(PivotItem, { key: `key-${i}`, headerText: categoryHeadings[key], headerButtonProps: {
                    'data-order': i,
                    'data-title': key
                }, alwaysRender: true },
                tags[key].map((t, i) => {
                    return React.createElement(Checkbox, { className: checkboxClassName, key: `checkBox_${i}`, label: t.message, onChange: (ev, checked) => onChange(key, checked !== null && checked !== void 0 ? checked : false, t.issue) });
                }),
                showFreeFormTextField && React.createElement(Checkbox, { checked: checkedTextFields.includes(key), styles: freeFormTextCheckboxStyles, onChange: (ev, checked) => onChange(key, checked !== null && checked !== void 0 ? checked : false), onRenderLabel: () => {
                        return onRenderLabel(key);
                    } }));
        })),
        React.createElement(Text, { className: helperTextStyle(theme) }, strings === null || strings === void 0 ? void 0 : strings.tagsSurveyHelperText));
};
//# sourceMappingURL=TagsSurvey.js.map