import React, { useCallback, useEffect, useState } from 'react';
import PropsTypes from 'prop-types';

const AutoFocusDialogContentContainer = props => {
    const { Component, open, children, ...otherProps } = props;
    const [contentRef, setContentRef] = useState(null);
    const [focusedOnce, setFocusedOnce] = useState(false);
    const focusFirstInteractiveElement = useCallback(element => {
        setContentRef(element);
    }, []);
    useEffect(() => {
        open && setFocusedOnce(false);
    }, [open]);
    useEffect(() => {
        if (!contentRef) {
            return;
        }
        const focusableElements = contentRef.querySelectorAll(
            'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
        );

        if (
            !focusedOnce &&
            focusableElements.length > 0 &&
            ![...focusableElements].some(element => element === document.activeElement)
        ) {
            const timeout = setTimeout(() => {
                const firstElement = focusableElements[0];
                firstElement.focus();
                setFocusedOnce(true);
            }, 100);
            return () => clearTimeout(timeout);
        }
    }, [children, focusedOnce, contentRef, focusFirstInteractiveElement]);
    return (
        <Component ref={focusFirstInteractiveElement} {...otherProps}>
            {children}
        </Component>
    );
};

AutoFocusDialogContentContainer.propTypes = {
    Component: PropsTypes.elementType,
    open: PropsTypes.bool,
    children: PropsTypes.node,
};

AutoFocusDialogContentContainer.defaultProps = {
    Component: 'div',
};

export default AutoFocusDialogContentContainer;
