import ClassName from 'classnames';
import noop from 'lodash/noop';
import sortBy from 'lodash/sortBy';
import React from 'react';
import {Responsive, WidthProvider} from 'react-grid-layout';

import './Dashboard.scss';

const BREAKPOINT_LG_MIN = 1024;
const BREAKPOINT_MD_MAX = 1023;

export const ControlledDashboard = (props) => {
  const isDesktop = React.useMemo(
    () => {
      return (props.width >= BREAKPOINT_LG_MIN);
    },
    [props],
  );

  const isReadOnly = React.useMemo(
    () => {
      return (props.readOnly || !isDesktop);
    },
    [props, isDesktop],
  );

  const layouts = React.useMemo(
    () => {
      const result = {
        lg: props.layout,
      };

      const lgLayout = sortBy(props.layout, layout => [layout.y, layout.x]);
      const mdLayout = [];
      let currentY = 0;
      for (let serviceLayout of lgLayout) {
        const newServiceLayout = {
          ...serviceLayout,
          w: 12,
          x: 0,
          y: currentY,
        };
        mdLayout.push(newServiceLayout);

        currentY += serviceLayout.h;
      }
      result.md = mdLayout;

      return result;
    },
    [props],
  );

  const className = ClassName('Dashboard', {
    'read-only': isReadOnly,
  });
  return (
    <div className={className}>
      <Responsive
        breakpoints={{lg: BREAKPOINT_MD_MAX, md: 0}}
        cols={{lg: 12, md: 12}}
        containerPadding={{lg: [10, 10], md: [10, 10]}}
        draggableHandle=".draggable-handle"
        isDraggable={!isReadOnly}
        isResizable={!isReadOnly}
        layouts={layouts}
        rowHeight={30}
        width={props.width}
        onLayoutChange={isReadOnly ? noop : props.onGridLayoutChange}
      >
        {props.children}
      </Responsive>
    </div>
  );
};
ControlledDashboard.displayName = 'Dashboard';

export const Dashboard = WidthProvider(ControlledDashboard);
