import React, { useEffect, useRef, useState } from 'react';

export interface CollapseProps {
  children: React.ReactNode;
  open?: boolean;
  defaultOpen?: boolean;
  /** 닫힘 상태일 때 높이 값이 필요할 시 사용 */
  closedHeight?: string;
}

export function Collapse(props: CollapseProps): React.ReactNode {
  const { children, closedHeight = '0' } = props;
  const [open, setOpen] = useState(() => {
    return props.open || props.defaultOpen || false;
  });

  useEffect(() => {
    if (props.open === undefined) return;
    setOpen(props.open);
  }, [props.open]);

  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!ref.current) return;
    ref.current.style.maxHeight = open
      ? `${ref.current.scrollHeight}px`
      : closedHeight;
  }, [closedHeight, open]);

  return (
    <div className="tipp-collapse" ref={ref}>
      {children}
    </div>
  );
}
