'use client';

import React, {FC} from 'react';

import {PopoverStyle as S} from './popover.style';
import {IPopover} from './popover.type';

/**
 * PopoverComponent is a reusable React component that renders a popover element with customizable styles and behaviors.
 * @version 0.0.3
 * @author Audrey Bozorgi
 */
export const PopoverComponent: FC<IPopover> = ({
    children,
    triggerElement,
    popover,
    containerClassName,
}) => {
    const [anchorEl, setAnchorEl] = React.useState<HTMLDivElement | null>(null);

    const handleClick = (event: React.MouseEvent<HTMLDivElement>) => {
        event.stopPropagation();
        setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
        setAnchorEl(null);
    };

    const open = Boolean(anchorEl);
    const id = open ? 'simple-popover' : undefined;

    return (
        <div dir='auto'>
            <div onClick={handleClick} className={containerClassName}>
                {triggerElement}
            </div>
            <S.StyledPopover
                id={id}
                anchorEl={anchorEl}
                onClose={handleClose}
                onClick={handleClose}
                open={open}
                {...popover}
            >
                {children}
            </S.StyledPopover>
        </div>
    );
};
