import React, { useMemo, useState, useEffect } from 'react';
import { pipe, propOr, pathEq, any } from 'ramda';
import classnames from 'classnames';
import i18n from 'ui-i18n';
import { checkCanDeleteAttribute, isReltioCrosswalk, isTempUri, getErrorMessage, hasAttributeDescendantsWithErrors, isAnalyticAttribute, Mode } from '@reltio/mdm-sdk';
import Button from '@mui/material/Button';
import DeleteIcon from '@mui/icons-material/Delete';
import Typography from '@mui/material/Typography';
import { SmallIconButton } from '../SmallIconButton';
import { withContext } from '../HOCs/withContext';
import { ArrowExpandButton } from '../ArrowExpandButton';
import { ErrorWrapper } from '../ErrorWrapper';
import { EditModeAttributesList } from '../EditModeAttributesList';
import { useAttributeValueConfigPermissions } from '../contexts/ConfigPermissionsContext';
import { isHighlightedErrorType, ScrollToElementContext } from '../contexts/ScrollToElementContext';
import { useScrollToAttributeError } from '../hooks/useScrollToAttributeError';
import { useStyles } from './styles';
var EditModeComplexAttribute = function (_a) {
    var _b;
    var label = _a.label, attributeTypesList = _a.attributeTypesList, attributeType = _a.attributeType, attributeValue = _a.attributeValue, children = _a.children, errors = _a.errors, ownError = _a.ownError, modeProp = _a.mode, metadata = _a.metadata, crosswalks = _a.crosswalks, lazy = _a.lazy, showEmptyEditors = _a.showEmptyEditors, onAddOneMore = _a.onAddOneMore, onAddAttributes = _a.onAddAttributes, onDeleteAttribute = _a.onDeleteAttribute, onChangeAttribute = _a.onChangeAttribute, additionalControlsRenderer = _a.additionalControlsRenderer, hideDeleteButton = _a.hideDeleteButton, state = _a.state, showNonOv = _a.showNonOv, isHighlightedPath = _a.isHighlightedPath, highlightedError = _a.highlightedError, _c = _a.expanded, expandedProp = _c === void 0 ? false : _c;
    var styles = useStyles();
    var deleted = state === 'deleted';
    var edited = state === 'edited';
    var uri = attributeValue.uri;
    var isNew = isTempUri(uri);
    var defaultExpand = isNew || expandedProp;
    var _d = useState(defaultExpand), expanded = _d[0], setExpanded = _d[1];
    var _e = useScrollToAttributeError({ highlightedError: highlightedError }), ref = _e.ref, errorClassName = _e.errorClassName;
    var mode = attributeValue.masked ? Mode.Viewing : modeProp;
    useEffect(function () {
        if (isHighlightedPath) {
            setExpanded(true);
        }
    }, [isHighlightedPath]);
    useEffect(function () {
        setExpanded(defaultExpand);
    }, [defaultExpand]);
    var configCanDelete = useAttributeValueConfigPermissions(attributeValue.uri).canDelete;
    var canDelete = useMemo(function () {
        return configCanDelete &&
            checkCanDeleteAttribute({
                attributeType: attributeType,
                attributeValue: attributeValue,
                mode: mode,
                metadata: metadata,
                isReltioCrosswalk: isReltioCrosswalk(crosswalks, attributeValue)
            });
    }, [attributeType, attributeValue, mode, metadata, crosswalks, configCanDelete]);
    var showDeleteButton = !deleted &&
        !hideDeleteButton &&
        !!onDeleteAttribute &&
        canDelete &&
        !attributeValue.masked &&
        mode !== Mode.Viewing;
    var onDeleteThis = function () { return onDeleteAttribute({ uri: uri, attributeType: attributeType, attributeValue: attributeValue }); };
    var hasDescendantsWithErrors = useMemo(function () { return hasAttributeDescendantsWithErrors(attributeValue, errors); }, [errors, attributeValue]);
    useEffect(function () {
        if (hasDescendantsWithErrors) {
            setExpanded(true);
        }
    }, [errors, hasDescendantsWithErrors]);
    useEffect(function () {
        if (deleted) {
            setExpanded(false);
        }
    }, [deleted]);
    var hasAnalyticValue = (attributeTypesList || []).some(function (attributeType) { return isAnalyticAttribute(attributeType); });
    var attributeListEntity = useMemo(function () {
        return ({
            attributes: hasAnalyticValue ? null : attributeValue.value,
            analyticsAttributes: hasAnalyticValue ? attributeValue.value : null
        });
    }, [attributeValue, hasAnalyticValue]);
    var errorMessage = getErrorMessage(ownError) || (hasDescendantsWithErrors && i18n.text('Has an incorrect value')) || '';
    return lazy ? (React.createElement(Button, { variant: "text", color: "primary", onClick: onAddOneMore }, "Create attribute")) : (React.createElement("div", { ref: ref, "data-reltio-id": "reltio-edit-mode-complex-attribute", className: classnames(styles.complexWrapper, errorClassName) },
        React.createElement("div", { className: styles.editor },
            React.createElement("div", { className: styles.titleContainer },
                React.createElement(ArrowExpandButton, { onClick: function () { return setExpanded(function (value) { return !value; }); }, expanded: expanded, className: styles.expandButton, disabled: deleted }),
                React.createElement(ErrorWrapper, { errorMessage: errorMessage, classes: { helperText: styles.errorWrapperHelperText } },
                    React.createElement("div", { className: classnames(styles.label, (_b = {}, _b[styles.deleted] = deleted, _b)), "data-reltio-id": "reltio-attribute-complex-label" }, label))),
            React.createElement("div", { "data-reltio-id": "reltio-complex-attribute-actions", className: styles.actions },
                edited && (React.createElement(Typography, { variant: "caption", className: styles.editedLabel },
                    "(",
                    i18n.text('edited'),
                    ")")),
                additionalControlsRenderer && additionalControlsRenderer({ attributeType: attributeType, attributeValue: attributeValue }),
                showDeleteButton && (React.createElement(SmallIconButton, { icon: DeleteIcon, onClick: onDeleteThis, size: "L", "data-reltio-id": "reltio-delete-complex-attribute-button" })))),
        expanded && (React.createElement(EditModeAttributesList, { parentAttributeType: attributeType, attrTypes: attributeTypesList, entity: attributeListEntity, showEmptyEditors: showEmptyEditors || isNew, drawLines: true, parentUri: uri, mode: mode, crosswalks: crosswalks, onAddAttributes: onAddAttributes, onChangeAttribute: onChangeAttribute, onDeleteAttribute: onDeleteAttribute, additionalControlsRenderer: additionalControlsRenderer, showNonOv: showNonOv }, children))));
};
export default withContext(ScrollToElementContext, function (contextValue, _a) {
    var attributeValue = _a.attributeValue;
    var _b = contextValue || {}, element = _b.element, type = _b.type;
    var isError = isHighlightedErrorType(type);
    var isHighlighted = isError && (element === null || element === void 0 ? void 0 : element.uri) === attributeValue.uri;
    var isHighlightedPath = isError && pipe(propOr([], 'path'), any(pathEq(['value', 'uri'], attributeValue.uri)))(element);
    return {
        highlightedError: isHighlighted ? contextValue : null,
        isHighlightedPath: isHighlightedPath
    };
}, EditModeComplexAttribute);
