import React, { useState } from 'react';

export interface ToolbarItemProps {
    children: React.ReactNode;
    renderContent?: (onClose: () => void) => React.ReactNode;
    onClick?: () => void;
    disabled?: boolean;
}

export const ToolbarItem: React.FC<ToolbarItemProps> = ({
    children,
    renderContent,
    onClick,
    disabled = false,
}) => {
    const [isOpen, setIsOpen] = useState(false);
    const [isFading, setIsFading] = useState(false);

    const handleClose = () => {
        setIsFading(true);
        setTimeout(() => {
            setIsOpen(false);
            setIsFading(false);
        }, 200);
    };

    const handleToggle = (e: React.MouseEvent) => {
        e.stopPropagation();
        if (disabled) return;

        if (renderContent) {
            if (isOpen) {
                handleClose();
            } else {
                setIsOpen(true);
            }
        }

        onClick?.();
    };

    return (
        <div className={`toolbar-item ${disabled ? 'disabled' : ''}`} onClick={handleToggle}>
            <div className='toolbar-item-content'>
                {children}
            </div>
            {renderContent && isOpen && !disabled && (
                <div
                    className={`toolbar-item-content-panel ${isFading ? 'fading' : ''}`}
                    onClick={(e) => e.stopPropagation()}
                >
                    {renderContent(handleClose)}
                </div>
            )}
        </div>
    );
};
