import React, { useCallback } from 'react';
import { connect } from 'react-redux';
import { Resizable } from 're-resizable';
import MouseTrap from 'mousetrap';
import Pages from './Pages';
import StatesContainer from './States';
import LayersContainer from '../../screen-edit/components/ScreenLayers/LayersContainer';
import { useSizeByDomId } from 'components/easyUse';
import { appActions } from '../models';
import styles from './index.less';

function LeftSider({ collapsed, width, updateLeftWidth, pages, panelId }) {
  const isAppEditHome = /\/app\/edit\/[0-9]+\/[0-9]+$/.test(window.location.pathname); // 是否终端编辑页首页
  const { width: windowWidth = 0, height: windowHeight = 0 } = useSizeByDomId();
  const adaptRuler = useCallback((_e, _direction, ref) => {
    MouseTrap.trigger('command+1');
    updateLeftWidth(parseInt(ref.style.width));
  }, []);

  return (
    <Resizable
      size={{ width, height: windowHeight - 64 }}
      enable={{ right: true }}
      minWidth={188}
      maxWidth={windowWidth - 660}
      onResizeStop={adaptRuler}
      style={{ display: collapsed ? 'none' : 'block' }}>
      <div className={styles.container}>
        {isAppEditHome && pages?.length > 1 && <Pages />}
        {!!panelId && <StatesContainer />}
        <LayersContainer type="mobile" />
      </div>
    </Resizable>
  );
}

const mapStateToProps = ({ interactionEdit, createApp, screensById }) => {
  const { leftCollapsed, id } = createApp;
  const { pages, leftBarWidth } = interactionEdit;
  const showPages = pages.filter((d) => !d.deleted);
  const screen = screensById[id];
  const panelId = screen?.panelId;

  return {
    panelId,
    pages: showPages,
    width: leftBarWidth,
    collapsed: leftCollapsed
  };
};

const mapDispatchToProps = {
  updateLeftWidth: appActions.updateLeftWidth
};

export default connect(mapStateToProps, mapDispatchToProps)(LeftSider);
