import React, { useEffect, useRef } from 'react';
import classnames from 'classnames';
import { getImageAttributeOvThumbnailUrl } from '@reltio/mdm-sdk';
import Grid from '@mui/material/Grid';
import { Image } from '../../../Image';
import { IMAGE_PADDING, IMAGE_WIDTH, CONTAINER_MARGIN } from './constants';
import { useStyles } from './styles';
export var Thumbnails = function (_a) {
    var attributeValues = _a.attributeValues, setAttributeValueIndex = _a.setAttributeValueIndex, attributeValueIndex = _a.attributeValueIndex;
    var styles = useStyles();
    var gridRef = useRef(null);
    useEffect(function () {
        if (gridRef === null || gridRef === void 0 ? void 0 : gridRef.current) {
            var containerScrollLeft = gridRef.current.scrollLeft;
            var containerOffsetWidth = gridRef.current.offsetWidth;
            var containerWidth = containerOffsetWidth + containerScrollLeft;
            var currentElementPosition = attributeValueIndex * IMAGE_WIDTH + attributeValueIndex * IMAGE_PADDING + CONTAINER_MARGIN;
            if (containerWidth < currentElementPosition) {
                if (gridRef.current.scroll) {
                    if (currentElementPosition > containerWidth + IMAGE_WIDTH + IMAGE_PADDING) {
                        gridRef.current.scroll(currentElementPosition, 0);
                    }
                    else {
                        gridRef.current.scroll(IMAGE_WIDTH + IMAGE_PADDING + containerScrollLeft, 0);
                    }
                }
            }
            else if (containerScrollLeft + IMAGE_WIDTH > currentElementPosition) {
                if (gridRef.current.scroll) {
                    gridRef.current.scroll(currentElementPosition - IMAGE_WIDTH, 0);
                }
            }
        }
    }, [attributeValueIndex, gridRef]);
    return (React.createElement("div", { ref: gridRef, className: styles.thumbnails },
        React.createElement(Grid, { "data-reltio-id": "thumbnails-container", container: true, wrap: "nowrap", direction: "row", spacing: 1, className: styles.gridContainer }, attributeValues.map(function (_a, index) {
            var _b;
            var uri = _a.uri, value = _a.value;
            return (React.createElement(Grid, { item: true, key: uri },
                React.createElement(Image, { onClick: function () { return setAttributeValueIndex(index); }, className: classnames(styles.thumb, (_b = {},
                        _b[styles.inactiveThumb] = attributeValueIndex !== index,
                        _b)), src: getImageAttributeOvThumbnailUrl({ value: value }) })));
        }))));
};
