import React, { memo, Fragment } from 'react';
import { connect } from 'react-redux';
import LayerOptionItem from './LayerOptionItem';
import LayerOptionGroup from './LayerOptionGroup';
import { selectLayerWithScrollIntoView } from 'models/create-app';
import styles from './LayerOptions.less';

function LayerOptions({
  visible,
  options,
  constants,
  layersSelected,
  level = 1,
  selectLayer
}: {
  visible?: boolean;
  options: any;
  constants: any;
  layersSelected: (string | number)[];
  level?: number;
  selectLayer: () => any;
}) {
  const Container = (props) =>
    level === 1 ? <div className={styles.container} style={{ display: visible ? 'block' : 'none' }} {...props} /> : <Fragment {...props} />;

  return (
    <Container>
      {options.map((d) => {
        if (d.components) {
          return (
            <div key={d.id}>
              <LayerOptionGroup
                id={d.id}
                selected={layersSelected.indexOf(d.id) > -1}
                level={level}
                name={d.name}
                lock={d.lock}
                onClick={selectLayer}
              />
              <LayerOptions
                options={d.components}
                constants={constants}
                layersSelected={layersSelected}
                level={level + 1}
                selectLayer={selectLayer}
              />
            </div>
          );
        } else {
          const constant = constants.find((v) => v.moduleName === d.moduleName) || {};

          return (
            <LayerOptionItem
              key={d.id}
              id={d.id}
              name={d.name}
              lock={d.lock}
              selected={layersSelected.indexOf(d.id) > -1}
              level={level}
              thumb={constant.thumb}
              onClick={selectLayer}
            />
          );
        }
      })}
    </Container>
  );
}

const mapStateToProps = ({ createApp, constants }) => {
  const { layersSelected } = createApp;

  return {
    constants: constants.list,
    layersSelected
  };
};

const mapDispatchToProps = {
  selectLayer: selectLayerWithScrollIntoView
};

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