import React, {ReactNode, useEffect, useRef, useState} from 'react';
import actions from '../../../../assets/images/actions.svg';
import close from '../../../../assets/images/close.png';

type ListActionsProps = {
    children?: ReactNode;
    flex?: string;
    label?: string;
    listView?: boolean;
};

const ListActions = ({children}: ListActionsProps) => {
    const [isOpen, setIsOpen] = useState(false);
    const [dropdownPosition, setDropdownPosition] = useState<'top' | 'bottom'>('top');
    const popupRef = useRef<HTMLDivElement>(null);


    // @ts-ignore
    const isEmpty = !children?.props?.children

    useEffect(() => {
        const handleClickOutside = (e: any) => {
            if (isOpen) {
                if (e.source && e.source.current === popupRef.current) return
                setIsOpen(false)
            }
        };

        window.addEventListener('click', handleClickOutside);

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

    const toggleDropdown = (e: React.MouseEvent) => {
        if (isEmpty) return
        // e.stopPropagation();
        setIsOpen((o) => !o);
    };

    /**
     * decide if the dropdown opens up or down (base on fitting the screen)
     * we dnt need another state and maybe usememo ??
     */
    useEffect(() => {
        if (isOpen && popupRef.current) {
            const dropdownRect = popupRef.current.getBoundingClientRect();
            const viewportHeight = window.innerHeight;
            const distanceFromBottom = viewportHeight - dropdownRect.bottom;
            if (distanceFromBottom <= 241) {
                setDropdownPosition('bottom');
            } else {
                setDropdownPosition('top');
            }
        }
    }, [isOpen]);


    return (
        <span className={`list-actions ${isEmpty && 'empty'}`} onClick={(e) => {
            // @ts-ignore
            e.nativeEvent.source = popupRef
            toggleDropdown(e)
        }} ref={popupRef}>
      <div className="list-actions--toggle">
        <span>
          <img src={actions} alt="" className={'px-2'}/>
        </span>
      </div>
            {isOpen && (
                <div
                    className={`list-actions--dropdown ${dropdownPosition === 'bottom' ? 'bottom-position' : ''}`}
                    onClick={(e) => e.stopPropagation()}
                >
                    <img
                        src={close}
                        alt=""
                        className={'close-btn'}
                        onClick={() => setIsOpen(false)}
                    />
                    {children}
                </div>
            )}
    </span>
    );
};

export default ListActions;
