import React, { useState, useContext, useEffect } from 'react';
import i18n from 'ui-i18n';
import classnames from 'classnames';
import { always, cond, T } from 'ramda';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import { useMdmUsername } from '../../../contexts/MdmModuleContext';
import { CollaborationContext } from '../../../contexts/CollaborationContext';
import { createCommentUri, transformPlainTextValueToValueWithMentions } from '../../helpers';
import { TextFieldWithMentions } from '../TextFieldWithMentions';
import { Avatar } from '../Avatar';
import { useStyles } from './styles';
var getPlaceholder = function (status) {
    switch (status) {
        case 'open':
            return i18n.text('Reply...');
        case 'resolved':
            return i18n.text('Adding a comment will re-open this');
        default:
            return '';
    }
};
var getButtonText = function (status, isEditingComment, isEditingReply) {
    if (isEditingComment || isEditingReply) {
        return i18n.text('Edit');
    }
    if (status === 'open' || status === 'resolved') {
        return i18n.text('Reply');
    }
    return i18n.text('Comment');
};
var getDefaultCommentState = function (_a) {
    var comment = _a.comment, reply = _a.reply, isEditingComment = _a.isEditingComment, isEditingReply = _a.isEditingReply;
    var commentOrReply = isEditingComment ? comment : isEditingReply ? reply : null;
    var _b = commentOrReply || {}, _c = _b.content, plainTextValue = _c === void 0 ? '' : _c, _d = _b.namedUsers, mentions = _d === void 0 ? [] : _d;
    return {
        value: transformPlainTextValueToValueWithMentions(plainTextValue, mentions),
        plainTextValue: plainTextValue,
        mentions: mentions
    };
};
export var SendMessageArea = function (_a) {
    var inputRef = _a.inputRef, className = _a.className, uri = _a.uri, relatedObjectUris = _a.relatedObjectUris, objectType = _a.objectType, popperRef = _a.popperRef, comment = _a.comment, reply = _a.reply, isEditingComment = _a.isEditingComment, isEditingReply = _a.isEditingReply, onCancel = _a.onCancel;
    var isEditing = isEditingComment || isEditingReply;
    var styles = useStyles({ isEditing: isEditing });
    var _b = useState(false), focused = _b[0], setFocused = _b[1];
    var _c = useContext(CollaborationContext), createReply = _c.createReply, createComment = _c.createComment, sending = _c.sending, editComment = _c.editComment, editReply = _c.editReply, getCommentState = _c.getCommentState, updateCommentState = _c.updateCommentState, clearCommentState = _c.clearCommentState;
    var username = useMdmUsername();
    var commentUri = createCommentUri({ comment: comment, reply: reply, isEditingComment: isEditingComment, isEditingReply: isEditingReply });
    var defaultCommentState = getDefaultCommentState({ comment: comment, reply: reply, isEditingComment: isEditingComment, isEditingReply: isEditingReply });
    var _d = getCommentState(uri, commentUri), _e = _d.value, value = _e === void 0 ? defaultCommentState.value : _e, _f = _d.plainTextValue, plainTextValue = _f === void 0 ? defaultCommentState.plainTextValue : _f, _g = _d.mentions, mentions = _g === void 0 ? defaultCommentState.mentions : _g;
    var hasDefaultValue = defaultCommentState.value.trim() !== '';
    var hasValue = value.trim() !== '';
    var shouldShowButtons = focused || hasValue || hasDefaultValue;
    var status = comment === null || comment === void 0 ? void 0 : comment.status;
    var clearValue = function () {
        onCancel === null || onCancel === void 0 ? void 0 : onCancel();
        clearCommentState(uri, commentUri);
    };
    var handleChange = function (value, plainTextValue, mentions) {
        return updateCommentState(uri, commentUri, { value: value, plainTextValue: plainTextValue, mentions: mentions });
    };
    var handleCancel = function () { return clearValue(); };
    var handleFocus = function () { return setFocused(true); };
    var handleBlur = function () { return setFocused(false); };
    var handleSubmit = function (e) {
        e.preventDefault();
        var request = cond([
            [
                always(!comment),
                function () {
                    return createComment({
                        content: plainTextValue,
                        namedUsers: mentions,
                        objectType: objectType,
                        uri: uri,
                        relatedObjectUris: relatedObjectUris
                    });
                }
            ],
            [
                always(isEditingComment),
                function () {
                    return editComment({
                        content: plainTextValue,
                        namedUsers: mentions,
                        commentId: comment.commentId,
                        objectType: objectType,
                        replies: comment.replies,
                        relatedObjectUris: relatedObjectUris,
                        uri: uri
                    });
                }
            ],
            [
                always(isEditingReply),
                function () {
                    return editReply({
                        content: plainTextValue,
                        namedUsers: mentions,
                        commentId: comment.commentId,
                        replyId: reply.replyId
                    });
                }
            ],
            [
                T,
                function () {
                    return createReply({
                        content: plainTextValue,
                        namedUsers: mentions,
                        commentId: comment.commentId,
                        action: comment.status === 'open' ? 'none' : 'reopen',
                        uri: uri
                    });
                }
            ]
        ]);
        return request().then(clearValue).catch(console.log); //eslint-disable-line no-console
    };
    useEffect(function () {
        if (popperRef) {
            popperRef.current.forceUpdate();
        }
    }, [popperRef, shouldShowButtons]);
    var buttonSize = isEditing ? 'small' : 'medium';
    return (React.createElement(Box, { className: classnames(styles.root, className) },
        React.createElement("form", { onSubmit: handleSubmit, className: styles.form },
            React.createElement(Box, { className: styles.main },
                !isEditing && React.createElement(Avatar, { classes: { root: styles.avatar } }, username),
                React.createElement(TextFieldWithMentions, { className: styles.textField, disabled: sending, onChange: handleChange, inputRef: inputRef, value: value, onFocus: handleFocus, onBlur: handleBlur, placeholder: getPlaceholder(status) })),
            shouldShowButtons && (React.createElement(Box, { className: styles.buttons },
                React.createElement(Button, { className: styles.button, variant: "contained", color: "primary", disabled: !hasValue || sending, type: "submit", size: buttonSize }, getButtonText(status, isEditingComment, isEditingReply)),
                React.createElement(Button, { disabled: sending, onClick: handleCancel, className: styles.button, variant: "outlined", color: "primary", size: buttonSize }, i18n.text('Cancel')))))));
};
