import PropTypes from 'prop-types';
import { Box } from '@mui/material';
import { useSize } from 'ahooks';
import { useEffect, useRef, useState } from 'react';

export default function AutoHeight({ children, initHeight = 0, slotProps = {} }) {
  const [maxHeight, setMaxHeight] = useState(initHeight);

  const contentRef = useRef(null);
  const contentSize = useSize(contentRef);

  useEffect(() => {
    if (contentSize?.height) {
      setMaxHeight(contentSize.height);
    }
  }, [contentSize?.height]);

  return (
    <Box
      {...slotProps?.root}
      sx={{
        height: maxHeight,
        overflow: 'hidden',
        transition: 'height 0.2s ease-in-out',
        ...slotProps?.root?.sx,
      }}>
      <Box {...slotProps?.container} ref={contentRef}>
        {children}
      </Box>
    </Box>
  );
}

AutoHeight.propTypes = {
  initHeight: PropTypes.number,
  children: PropTypes.node.isRequired,
  slotProps: PropTypes.object,
};
