import React, { Component } from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import { withRouter } from 'react-router-dom';
import CustomIcon from 'components/items/CustomIcon';
import ModuleButton from 'components/items/ModuleButton';
import styleIdentifiers from './moduleDetailStructure.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type ModuleDetailStructureProps = StateProps & DispatchProps & OwnProps;

interface ModuleDetailStructureState {}

function ModuleDetailStructure(ItemComponent: React.ComponentType<any>) {
  class DetailStructure extends React.Component<
    ModuleDetailStructureProps,
    ModuleDetailStructureState
  > {
    returnFieldsPart(isOption) {
      const { items } = this.props;

      const list = items.filter(e => {
        let isInOptions = false;

        if (typeof e === 'object') {
          const inArray = Object.values(e);
          if (inArray.filter(i => !i.side).length === 0) isInOptions = true;
        }

        if (isOption) return isInOptions;
        return !isInOptions;
      });

      return list;
    }

    renderAction() {
      const { actions } = this.props;
      if (!actions) return null;

      return (
        <div className={styles('action-container')}>
          {actions.map((item, key) => (
            <ModuleButton key={key} {...item} noMargin />
          ))}
        </div>
      );
    }

    renderHeader() {
      const { title, history } = this.props;
      if (!title) return null;

      return (
        <div className={styles('header')}>
          <div className={styles('back')} onClick={() => history.goBack()}>
            <CustomIcon className={styles('icon')} icon="angle-left" />
            <TextItem path="admin.buttons.back" />
          </div>
          <div className={styles('title')}>{title}</div>
        </div>
      );
    }

    render() {
      const { actions } = this.props;
      return (
        <div className={styles('ModuleDetailStructure')}>
          <div className={styles('general')}>
            {this.renderHeader()}
            {this.returnFieldsPart().map((item, key) => (
              <ItemComponent {...this.props} item={item} key={key} />
            ))}
          </div>
          {(this.returnFieldsPart(true).length !== 0 || actions) && (
            <div className={styles('options')}>
              {this.renderAction()}
              {this.returnFieldsPart(true).map((item, key) => (
                <ItemComponent {...this.props} item={item} key={key} />
              ))}
            </div>
          )}
        </div>
      );
    }
  }
  return withRouter(DetailStructure);
}

export default ModuleDetailStructure;
