import React, { useRef, useState, useEffect } from 'react';
import RGL, { WidthProvider } from 'react-grid-layout';
import { getPrefixedClassName } from '../utils';
import { LayoutProps } from './types';

const ReactGridLayout = WidthProvider(RGL);

const Layout: React.FC<LayoutProps> = (props) => {
  const { layouts, resizable, draggable, margin = [0, 0], children, onLayoutChange } = props;
  const containerRef = useRef<HTMLDivElement>();
  const [rowHeight, setRowHeight] = useState<number>(0);

  const changRowHeight = () => {
    /**
     * Split height to 12 grids
     * If there is the y margin prop, it will have 11 actual y margins, which need to be subtracted from the container height.
     */
    setRowHeight((containerRef.current.clientHeight - margin[1] * 11) / 12);
  };

  useEffect(() => {
    // Monitor window resizing triggering canvas container change
    window.addEventListener('resize', changRowHeight);

    return () => {
      window.removeEventListener('resize', changRowHeight);
    };
  }, []);

  useEffect(() => {
    if (containerRef.current) {
      changRowHeight();
    }
  }, [containerRef]);

  return (
    <div className={getPrefixedClassName('layout-container')} ref={containerRef}>
      {!!rowHeight && (
        <ReactGridLayout
          className={getPrefixedClassName('layout')}
          layout={layouts}
          useCSSTransforms={true}
          allowOverlap={true}
          cols={12}
          rowHeight={rowHeight}
          autoSize={false}
          // If the component can be destroyed when it is dragged to the outside, the property can be false
          isBounded={true}
          margin={margin}
          containerPadding={[0, 0]}
          isResizable={resizable}
          isDraggable={draggable}
          onLayoutChange={onLayoutChange}
        >
          {children}
        </ReactGridLayout>
      )}
    </div>
  );
};

export default Layout;
