import React, { useCallback, useMemo, useState } from 'react';
import i18n from 'ui-i18n';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import { DCROperationTypes, getImageAttributeThumbnailUrl } from '@reltio/mdm-sdk';
import { SmallIconButton } from '../../../../../SmallIconButton';
import { UploadImageDialog } from '../../../../../UploadImageDialog';
export var DCRImageEditor = function (_a) {
    var change = _a.change, onUpload = _a.onUpload, disabled = _a.disabled;
    var attributeType = change.attributeType;
    var isDeleted = change.operation === DCROperationTypes.DELETED;
    var thumbnailUrl = useMemo(function () {
        var _a, _b;
        var innerChange = (_a = change.attributeValue) === null || _a === void 0 ? void 0 : _a.value;
        var imageSource = (_b = innerChange === null || innerChange === void 0 ? void 0 : innerChange.newValue) !== null && _b !== void 0 ? _b : change.attributeValue;
        return getImageAttributeThumbnailUrl((imageSource !== null && imageSource !== void 0 ? imageSource : {}));
    }, [change.attributeValue]);
    var _b = useState(false), isDialogOpen = _b[0], setIsDialogOpen = _b[1];
    var _c = useState(null), uploadedThumbnailUrl = _c[0], setUploadedThumbnailUrl = _c[1];
    var toggleDialog = useCallback(function () {
        setIsDialogOpen(function (prev) { return !prev; });
    }, []);
    var handleUpload = useCallback(function (image) {
        var imageValue = {};
        var subAttributes = (attributeType === null || attributeType === void 0 ? void 0 : attributeType.attributes) || [];
        var _loop_1 = function (key) {
            if (subAttributes.some(function (_a) {
                var name = _a.name;
                return name === key;
            })) {
                imageValue[key] = [{ value: image[key] }];
            }
        };
        for (var key in image) {
            _loop_1(key);
        }
        onUpload({ value: imageValue });
        setUploadedThumbnailUrl(image.CdnUrlThumbnail || image.CdnUrl || null);
    }, [attributeType, onUpload]);
    var isDisabled = disabled || isDeleted;
    var displayUrl = uploadedThumbnailUrl || thumbnailUrl;
    return (React.createElement(React.Fragment, null,
        displayUrl ? (React.createElement("img", { src: displayUrl, alt: "", style: {
                maxWidth: 80,
                maxHeight: 80,
                objectFit: 'cover',
                cursor: isDisabled ? 'default' : 'pointer'
            }, onClick: isDisabled ? undefined : toggleDialog })) : (React.createElement(SmallIconButton, { icon: CloudUploadIcon, onClick: toggleDialog, title: i18n.text('Upload image'), disabled: isDisabled })),
        React.createElement(UploadImageDialog, { open: isDialogOpen, onUpload: handleUpload, onClose: toggleDialog })));
};
