import { Card, Popover, Icon } from '@servicetitan/design-system';
import { FC, useState, useRef, useEffect, ReactNode } from 'react';

import * as Styles from './actions-button.module.less';

export const ActionsButton: FC<{
    children: ReactNode;
}> = ({ children }) => {
    const [isOpen, setIsOpen] = useState(false);
    const wrapElem = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClick = (event: MouseEvent) => {
            if (!wrapElem.current) {
                return;
            }

            const isClickedInside = wrapElem.current.contains(event.target as Node);

            if (!isClickedInside) {
                close();
            }
        };

        window.addEventListener('click', handleClick);

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

    const toggle = () => {
        setIsOpen(!isOpen);
    };

    const close = () => {
        setIsOpen(false);
    };

    return (
        <div
            ref={wrapElem}
            className="qa-actions-button d-ib"
            onClick={e => {
                e.stopPropagation();
            }}
        >
            <Popover
                className={Styles.popover}
                width="xs"
                open={isOpen}
                direction="bl"
                trigger={
                    <Card
                        raised
                        sharp
                        padding="none"
                        active={isOpen}
                        onClick={toggle}
                        className="qa-actions-button-menu-button"
                    >
                        <Card.Section className="p-half-i">
                            <Icon
                                name="more_vert"
                                size="22px"
                                className={isOpen ? 'c-blue-400' : ''}
                            />
                        </Card.Section>
                    </Card>
                }
            >
                {children}
            </Popover>
        </div>
    );
};
