import React, { useRef, useState } from 'react';
import PropTypes from 'prop-types';

import Icon from '../../../icon/Icon';
import Button from '../../../button/Button';
import { createNamespace } from '../../../../tools/namingTools';
import { ReportRect } from '../../../../tools/dimensions/reportRect';
import './styles/ModalContents.scss';

const n = createNamespace('ModalContents');

const minimumEdgeDistance = 10; // px

const ModalContents = ({
    children,
    onClose,
    animTime,
    left: originalLeft,
    top: originalTop
}) => {
    const contentRef = useRef(null);
    const [isCentered, setIsCentered] = useState(false);
    const [translatedTop, setTranslatedTop] = useState(0);
    const [translatedLeft, setTranslatedLeft] = useState(0);

    ReportRect(contentRef, rect => {
        const availableWidth = window.innerWidth;
        const availableHeight = window.innerHeight;
        const { left, width, height, right, bottom } = rect;
        const realBottom = bottom - translatedTop;
        const realLeft = left - translatedLeft;
        const realRight = right - translatedLeft;
        // window can fit only one element, center it
        if (availableWidth < width * 2) {
            setIsCentered(true);
        } else if (realLeft < 0) {
            setTranslatedLeft(-realLeft + minimumEdgeDistance);
        } else if (realRight > availableWidth) {
            setTranslatedLeft((availableWidth - realRight) - minimumEdgeDistance);
        }
        if (realBottom > availableHeight && height < availableHeight) {
            setTranslatedTop(availableHeight - realBottom - minimumEdgeDistance);
        }
    });

    const wrapperProps = n('content', isCentered && 'centered').withVariables({
        animTime: `${animTime}ms`,
        left: `${originalLeft}px`,
        top: `${originalTop}px`,
        translatedTop: `${translatedTop}px`,
        translatedLeft: `${translatedLeft}px`
    }).props;
    return (
        <div {...wrapperProps} ref={contentRef}>
            <div {...n('closeButton').props}>
                <Button buttonType="icon" onClick={onClose}>
                    <span {...n('closeButtonText').props}>X</span>
                    <Icon {...n('closeButtonIcon').props} type="close" />
                </Button>
            </div>
            <div>
                {children}
            </div>
        </div>
    );
};

ModalContents.propTypes = {
    onClose: PropTypes.func,
    animTime: PropTypes.number,
    left: PropTypes.number,
    top: PropTypes.number
};

ModalContents.defaultProps = {
    onClose: () => null,
    animTime: 0,
    left: 0,
    top: 0
};

export default ModalContents;
