import { __read } from "tslib";
import React, { useState, useEffect, useRef, useMemo } from "react";
import { createPortal } from "react-dom";
import { calculateSizeAnPositionElement } from "../helpers/getPosition/helpers";
import PopoverContent from "./components/PopoverContent";
import { PopoverStyled } from "./styles";
var Popover = function (_a) {
    var children = _a.children, _b = _a.direction, direction = _b === void 0 ? "top" : _b, title = _a.title, description = _a.description, primaryButtonContent = _a.primaryButtonContent, secondaryButtonContent = _a.secondaryButtonContent, _c = _a.isPrimaryButton, isPrimaryButton = _c === void 0 ? primaryButtonContent !== undefined : _c, _d = _a.isSecondaryButton, isSecondaryButton = _d === void 0 ? secondaryButtonContent !== undefined : _d, onPrimaryButton = _a.onPrimaryButton, onSecondaryButton = _a.onSecondaryButton, onVisibleChange = _a.onVisibleChange, _e = _a.defaultIsVisible, defaultIsVisible = _e === void 0 ? false : _e, className = _a.className, _f = _a.isShow, isShow = _f === void 0 ? true : _f;
    var _g = __read(useState(false), 2), isVisible = _g[0], setIsVisible = _g[1];
    var _h = __read(useState(null), 2), containerPopover = _h[0], setContainerPopover = _h[1];
    var anchorComponentRef = useRef(null);
    var anchorSizeAndPosition = useMemo(function () { return calculateSizeAnPositionElement(anchorComponentRef.current); }, [isVisible]);
    useEffect(function () {
        var container = document.getElementsByTagName("body").item(0);
        setContainerPopover(container);
        if (defaultIsVisible) {
            setIsVisible(defaultIsVisible);
        }
    }, []);
    useEffect(function () {
        onVisibleChange && onVisibleChange(isVisible || false);
    }, [isVisible]);
    var handleMouseClick = function () {
        setIsVisible(isShow);
    };
    var handleClose = function () {
        setIsVisible(false);
    };
    return (React.createElement(PopoverStyled, { ref: anchorComponentRef, onMouseDown: handleMouseClick, onBlur: handleClose, className: className },
        children,
        containerPopover &&
            isVisible &&
            createPortal(React.createElement(PopoverContent, { direction: direction, anchorSizeAndPosition: anchorSizeAndPosition, title: title, description: description, isPrimaryButton: isPrimaryButton, isSecondaryButton: isSecondaryButton, primaryButtonContent: primaryButtonContent, secondaryButtonContent: secondaryButtonContent, onPrimaryButton: onPrimaryButton, onSecondaryButton: onSecondaryButton, handleClose: handleClose }), containerPopover)));
};
Popover.displayName = "Popover";
export default Popover;
