/* eslint-disable react-hooks/exhaustive-deps */
import React, { useCallback, useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Resizable } from 're-resizable';
import Mousetrap from 'mousetrap';
import LayersContainer from './LayersContainer';
import StatesContainer from './States';
import { useSizeByDomId } from 'components/easyUse';
import { updateScreen } from 'models/screens';

import styles from './index.less';

function ScreenLayers({ id, collapsed, width = 188, panelId, dispatch }) {
  const { width: windowWidth = 0, height: windowHeight = 0 } = useSizeByDomId();
  const [_width, setWidth] = useState(width);

  const adaptRuler = useCallback(
    (_e, _direction, ref) => {
      Mousetrap.trigger('command+1');
      const value = parseInt(ref.style.width);
      setWidth(value);
      dispatch(updateScreen({ id, leftBarWidth: value }));
    },
    [id]
  );

  useEffect(() => {
    setWidth(width);
  }, [width]);

  return (
    <Resizable
      size={{ width: _width, height: windowHeight - 64 }} //不能设置为auto，这样宽高改变的时候scrollTop就会置为0
      enable={{ right: true }}
      minWidth={188}
      maxWidth={windowWidth - 660}
      onResizeStop={adaptRuler}
      style={{ display: collapsed ? 'none' : 'block' }}
      handleClasses={{ right: styles.handle }}
      handleStyles={{ right: { width: 3, right: 0 } }}>
      <div className={styles.container}>
        {!!panelId && <StatesContainer />}
        <LayersContainer />
      </div>
    </Resizable>
  );
}

const mapStateToProps = ({ createApp, screensById }) => {
  const { id, leftCollapsed } = createApp;
  const screen = screensById[id];
  let width;
  let panelId;
  if (screen) {
    const { leftBarWidth } = screen;
    width = leftBarWidth;
    panelId = screen.panelId;
  }

  return {
    id,
    width,
    panelId,
    collapsed: leftCollapsed
  };
};

export default connect(mapStateToProps)(ScreenLayers);
