import React, { ReactNode, useState, useEffect, useRef } from 'react';
import './button-with-popup.scss';

type ButtonProps = {
    type: 'button' |'submit'
    onClick?: () => void;
    buttonText: string;
    buttonIcon: JSX.Element;
    children: ReactNode;
};

const ButtonWithPopup: React.FC<ButtonProps> = ({
                                                    onClick,
                                                    buttonText,
                                                    buttonIcon,
                                                    children,
    type,
                                                }) => {
    const [showPopup, setShowPopup] = useState(false);
    const buttonRef = useRef<HTMLButtonElement>(null);
    const popupRef = useRef<HTMLDivElement>(null);

    const handleButtonClick = () => {
        setShowPopup(!showPopup);
        onClick && onClick();
    };

    const handleClickOutside = (event: MouseEvent) => {
        if (
            buttonRef.current &&
            !buttonRef.current.contains(event.target as Node) &&
            popupRef.current &&
            !popupRef.current.contains(event.target as Node)
        ) {
            setShowPopup(false);
        }
    };

    useEffect(() => {
        window.addEventListener('click', handleClickOutside);
        return () => {
            window.removeEventListener('click', handleClickOutside);
        };
    }, []);

    return (
        <>
            <button type={type} className={'popup-button'} onClick={handleButtonClick} ref={buttonRef}>
                {buttonIcon}
                <p>{buttonText}</p>
            </button>
            {showPopup && (
                <div className={'popup-container'} ref={popupRef}>
                    {children}
                </div>
            )}
        </>
    );
};

export default ButtonWithPopup;
