import React, { useMemo, useCallback, useContext } from 'react';
import { useContextSelector } from '@fluentui/react-context-selector';
import { isNil } from 'ramda';
import Accordion from '@mui/material/Accordion';
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { useChangesList } from '../../../hooks/useChangesList';
import { DCREntityUriLink } from '../../../DCREntityUriLink/DCREntityUriLink';
import { ChangeItemRow } from '../ChangeItemRow/ChangeItemRow';
import { useMdmMetadata } from '../../../../../contexts/MdmModuleContext';
import { AddedAttributesContext } from '../../../contexts/AddedAttributesContext';
import { ScrollToAddedAttributeContext } from '../../../contexts/ScrollToAddedAttributeContext';
import { AttributesChangesContext } from '../../../AttributesChanges/AttributesChangesContext';
import { getDCRUri } from '../../../helpers/common';
import { getAvailableAttributeTypesForEntity, getAvailableAttributeTypesForRelation, getAvailableSubAttributesForNestedOrReference } from '../../../helpers/moreAttributesScope';
import { isDiffChange, isRelationRow, isNestedOrReferenceParent } from '../../helpers/helpers';
import { prepareChangesList } from '../../helpers/changesList';
import { extractChangeOverrides, getAddedId, getParentAddedId, getParentChangeOverrides, getParentLineId, isRootAddedAttribute } from '../../helpers/addedAttributes';
import { extractLineIds } from '../../../helpers/merge';
import { useDcrReviewAllowAddAttributes } from '../../hooks/useDcrReviewAllowAddAttributes';
import { MoreAttributesEditor } from '../editors';
import styles from './EntityChangesGroup.module.css';
export var EntityChangesGroup = function (_a) {
    var task = _a.task, dcr = _a.dcr, entityInfo = _a.entityInfo, relationsInfo = _a.relationsInfo;
    var metadata = useMdmMetadata();
    var dcrUri = getDCRUri(task.objectURIs);
    var _b = dcr || {}, changes = _b.changes, objectsInfo = _b.objectsInfo;
    var addAddedAttributes = useContextSelector(AddedAttributesContext, function (ctx) { return ctx.addAddedAttributes; });
    var highlight = useContext(ScrollToAddedAttributeContext).highlight;
    var allowAddAttributes = useDcrReviewAllowAddAttributes();
    var rawChangesList = useChangesList({
        changes: changes,
        entityInfo: entityInfo,
        relationsInfo: relationsInfo
    });
    var changesList = useMemo(function () { return prepareChangesList(rawChangesList); }, [rawChangesList]);
    var objectUriByChangeIndex = useMemo(function () {
        var _a, _b;
        var result = [];
        var currentObjectUri = entityInfo.uri;
        for (var _i = 0, changesList_1 = changesList; _i < changesList_1.length; _i++) {
            var item = changesList_1[_i];
            if (!isDiffChange(item)) {
                currentObjectUri = entityInfo.uri;
            }
            else if (isRelationRow(item)) {
                currentObjectUri = (_b = (_a = item.attributeValue) === null || _a === void 0 ? void 0 : _a.uri) !== null && _b !== void 0 ? _b : entityInfo.uri;
            }
            result.push(currentObjectUri);
        }
        return result;
    }, [changesList, entityInfo.uri]);
    var entityAttributeTypes = useMemo(function () {
        if (!isNil(entityInfo.isExist)) {
            return getAvailableAttributeTypesForEntity(metadata, entityInfo.type);
        }
        return [];
    }, [metadata, entityInfo.type, entityInfo.isExist]);
    var relationAttributeTypesMap = useMemo(function () {
        var map = new Map();
        for (var _i = 0, relationsInfo_1 = relationsInfo; _i < relationsInfo_1.length; _i++) {
            var relationInfo = relationsInfo_1[_i];
            if (!map.has(relationInfo.type)) {
                map.set(relationInfo.type, getAvailableAttributeTypesForRelation(metadata, relationInfo.type));
            }
        }
        return map;
    }, [metadata, relationsInfo]);
    var handleAddAttributes = useCallback(function (_a) {
        var objectUri = _a.objectUri, parentLineId = _a.parentLineId, parentId = _a.parentId, changeOverrides = _a.changeOverrides;
        return function (attributeTypes) {
            var addedIds = addAddedAttributes({
                attributeTypes: attributeTypes,
                objectUri: objectUri,
                parentLineId: parentLineId,
                parentId: parentId,
                changeOverrides: changeOverrides
            });
            highlight(addedIds);
        };
    }, [addAddedAttributes, highlight]);
    var handleAddNestedAttributes = useCallback(function (change, objectUri) { return function (attributeTypes) {
        var _a, _b, _c, _d, _e;
        var parentUri = (_a = change.attributeType) === null || _a === void 0 ? void 0 : _a.uri;
        var parentAttrs = attributeTypes.filter(function (attr) { return attr.uri === parentUri; });
        var subAttrs = attributeTypes.filter(function (attr) { return attr.uri !== parentUri; });
        var childOverrides = extractChangeOverrides(change);
        var siblingOverrides = getParentChangeOverrides(change);
        if (parentAttrs.length > 0) {
            var lineId = (_c = (_b = change.lineIds) === null || _b === void 0 ? void 0 : _b[0]) !== null && _c !== void 0 ? _c : (_d = extractLineIds(change.newValue)) === null || _d === void 0 ? void 0 : _d[0];
            var addedId = getAddedId(change);
            if (lineId && isRootAddedAttribute(lineId)) {
                handleAddAttributes({
                    objectUri: objectUri,
                    changeOverrides: siblingOverrides
                })(parentAttrs);
            }
            else if (lineId) {
                handleAddAttributes({
                    parentLineId: getParentLineId(lineId),
                    parentId: addedId ? getParentAddedId(addedId) : undefined,
                    changeOverrides: siblingOverrides
                })(parentAttrs);
            }
            else {
                handleAddAttributes({
                    objectUri: objectUri,
                    changeOverrides: siblingOverrides
                })(parentAttrs);
            }
        }
        if (subAttrs.length > 0) {
            var parentLineId = (_e = change.lineIds) === null || _e === void 0 ? void 0 : _e[0];
            var parentId = change.addedId;
            if (parentLineId || parentId) {
                handleAddAttributes({ parentLineId: parentLineId, parentId: parentId, changeOverrides: childOverrides })(subAttrs);
            }
            else {
                handleAddAttributes({
                    objectUri: objectUri,
                    changeOverrides: childOverrides
                })(subAttrs);
            }
        }
    }; }, [handleAddAttributes]);
    return (React.createElement(AttributesChangesContext.Provider, { value: objectsInfo },
        React.createElement(Accordion, { className: styles.entityGroup, defaultExpanded: true, "data-reltio-id": "entity-changes-group" },
            React.createElement(AccordionSummary, { expandIcon: React.createElement(ExpandMoreIcon, null), className: styles.entityHeader, classes: {
                    content: styles.accordionContent
                } },
                React.createElement(DCREntityUriLink, { entityInfo: entityInfo, changes: changes, dcrUri: dcrUri, className: styles.entityTitle })),
            React.createElement(AccordionDetails, { className: styles.attributesList },
                allowAddAttributes && entityAttributeTypes.length > 0 && (React.createElement(MoreAttributesEditor, { data: entityAttributeTypes, onApply: handleAddAttributes({ objectUri: entityInfo.uri }) })),
                changesList.map(function (item, index) {
                    var _a, _b, _c, _d, _e, _f;
                    if (!isDiffChange(item)) {
                        return (React.createElement("div", { key: "title-".concat(index), className: styles.titleChangeItem }, item.label));
                    }
                    var relationAttrs = item.relationType
                        ? ((_a = relationAttributeTypesMap.get(item.relationType.uri)) !== null && _a !== void 0 ? _a : [])
                        : [];
                    var nestedAttrs = isNestedOrReferenceParent(item)
                        ? getAvailableSubAttributesForNestedOrReference(metadata, item.attributeType)
                        : [];
                    var changeKey = (_d = (_b = item.addedId) !== null && _b !== void 0 ? _b : (_c = item.attributeValue) === null || _c === void 0 ? void 0 : _c.uri) !== null && _d !== void 0 ? _d : "change-".concat(index);
                    return (React.createElement(React.Fragment, { key: changeKey },
                        React.createElement(ChangeItemRow, { change: item, entityInfo: entityInfo }),
                        allowAddAttributes && isRelationRow(item) && (React.createElement(MoreAttributesEditor, { data: relationAttrs, change: item, onApply: handleAddAttributes({
                                objectUri: (_e = item === null || item === void 0 ? void 0 : item.attributeValue) === null || _e === void 0 ? void 0 : _e.uri,
                                parentLineId: (_f = item.lineIds) === null || _f === void 0 ? void 0 : _f[0]
                            }) })),
                        allowAddAttributes && isNestedOrReferenceParent(item) && (React.createElement(MoreAttributesEditor, { data: nestedAttrs, change: item, parent: item.attributeType, onApply: handleAddNestedAttributes(item, objectUriByChangeIndex[index]) }))));
                })))));
};
