import React, { useEffect, useRef, ReactNode } from 'react';
import cx from 'classnames';

interface Props {
  children?: ReactNode;
  isCollapsed: boolean;
  printViewAlawaysExpanded: boolean;
}

const Collapsible = ({ children, isCollapsed, printViewAlawaysExpanded }: Props) => {
  const rootElementRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (rootElementRef.current === null || rootElementRef.current.children.length === 0) {
      return;
    }

    rootElementRef.current.style.maxHeight = `${(rootElementRef.current.children[0] as HTMLElement).offsetHeight}px`;
  }, [ rootElementRef, (rootElementRef?.current?.children[0] as HTMLElement)?.offsetHeight ]);

  const containerClassNames = cx(
    'u-collapsible',
    { 'u-collapsible--collapsed': isCollapsed },
    { 'u-collapsible--print-always-expanded': printViewAlawaysExpanded },
  );

  return (
    <div className={containerClassNames} ref={rootElementRef}>
      {children}
    </div>
  );
};

export { Collapsible };
