import React, { memo, useRef } from 'react';
import { connect } from 'react-redux';
import classNames from 'classnames';
import ThemeItem from './Item';
import { applyTheme } from 'models/theme';
import { Icon } from 'components/easyDesign';
import { useClickOutside } from 'components/easyUse';
import ThemeAdd from './Add';
import styles from './List.less';

function ThemeList({ admin, visible, thumb, themes, supportTheme, applyTheme, onMouseLeave }) {
  const containerRef = useRef(null);

  useClickOutside(containerRef, () => {
    if (visible) {
      onMouseLeave();
    }
  });

  return (
    <div
      ref={containerRef}
      className={classNames(styles.container, { [styles.visible]: visible })}
      style={{ overflowY: 'auto' }}
      onMouseLeave={onMouseLeave}>
      <div className={styles.content}>
        <ThemeItem name="系统默认" thumb={thumb} onClick={applyTheme} />

        {themes.map((d) => (
          <ThemeItem
            key={d.id}
            id={d.id}
            name={d.name}
            thumb={d.thumb}
            lock={!supportTheme}
            isDefault={d.isDefault}
            onClick={applyTheme}
          />
        ))}

        {admin && (
          <ThemeAdd>
            <div className={styles.add}>
              <Icon type="icon_add" style={{ fontSize: 30 }} />
            </div>
          </ThemeAdd>
        )}
      </div>
    </div>
  );
}

const mapStateToProps = ({ user, createApp, componentsById, themes, constants }) => {
  const { layersSelected } = createApp;
  const { edition = {}, role } = user.userInfo;
  const { supportTheme } = edition;
  const componentId = layersSelected[0];
  const component = componentsById[componentId];
  const { base } = component;
  const { module_name: moduleName } = base;
  const showedThemes = themes.list.filter((d) => d.published && d.moduleName === moduleName);
  const constant = constants.list.find((d) => d.moduleName === moduleName) || {};

  return {
    admin: role > 0,
    themes: showedThemes,
    thumb: constant.thumb,
    supportTheme: window.appConfig.LOCAL ? true : supportTheme,
  };
};

const mapDispatchToProps = {
  applyTheme,
};

export default connect(mapStateToProps, mapDispatchToProps)(memo(ThemeList));
