import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import _ from 'lodash';
import moment from 'moment';
import FontAwesome from 'react-fontawesome';
import Config, { PlussCore } from '../feature.config';
import { jobsLoaded } from '../actions';
import { maintenanceActions } from '../apis';
import JobList from '../components/JobList';
import JobTypes from '../components/JobTypes';
import Configuration from '../components/Configuration';
import { values } from '../values.config';

const { Components, Session, Urls } = PlussCore;

class RequestsHub extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedSection: 'all',
      location: '',
      loadingAll: false,
      loadingSubmissions: false,
      submissionEntries: [],
      allList: [],
      completed: [],
      upcoming: [],
      now: moment.utc(),
      onlyFuture: true,
      search: '',
    };
  }

  UNSAFE_componentWillMount() {
    this.updateProps(this.props);
  }

  componentDidMount() {
    this.getData();
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (!_.isEqual(this.props.jobs, nextProps.jobs)) this.updateProps(nextProps);
  }

  updateProps(props) {
    this.setState({ allList: props.jobs }, this.setData);
  }

  setData = () => {
    const allList = [];

    this.state.allList.forEach((ev) => {
      if (ev != null && !ev.Deleted) allList.push(ev);
    });

    const upcoming = _.filter(allList, (ev) => {
      if (!ev) return false;
      if (ev.status && ev.status === 'Completed') return false;
      return true;
    });

    const completed = _.filter(allList, (ev) => {
      if (!ev) return false;
      if (ev.status && ev.status === 'Completed') return true;
      return false;
    });

    // console.log('setData', upcoming, completed);
    this.setState({ allList, upcoming, completed });
  };

  getData = () => {
    const { auth } = this.props;
    this.setState({ loadingAll: true }, async () => {
      try {
        const res = await maintenanceActions.getJobsRecursive(auth.site);
        this.setState({ loadingAll: false });
        if (!_.isEmpty(res) && res[0].site === auth.site) {
          this.props.jobsLoaded(res);
        }
      } catch (error) {
        console.error('getData', error);
        this.setState({ loadingAll: false });
      }
    });
  };

  onAddNew = () => {
    const { auth } = this.props;
    if (Session.validateAccess(auth.site, values.permissionMaintenanceTracking, auth)) {
      this.props.history.push(values.routeAddRequest);
    }
  };

  onAddRequestType = () => {
    const { auth } = this.props;
    if (Session.validateAccess(auth.site, values.permissionMaintenanceTypes, auth)) {
      this.props.history.push(values.routeAddRequestType);
    }
  };

  canAddNew = (isClass) => {
    const { auth } = this.props;
    if (Session.validateAccess(auth.site, values.permissionMaintenanceTracking, auth)) return isClass ? '' : true;
    return isClass ? ' hub-sideContent-topButton--hide' : false;
  };

  getSideBarSectionColour = (id) => (this.state.selectedSection === id ? { backgroundColor: '#fff' } : {});

  renderStats = (stat, loading) => (loading ? <FontAwesome style={styles.spinner} name="spinner fa-pulse fa-fw" /> : stat);

  renderLeftBar() {
    const sectionItems = [];

    if (this.canAddNew()) {
      sectionItems.push({
        type: 'newButton',
        text: `New ${values.textSingularName}`,
        onClick: this.onAddNew,
      });
    }

    sectionItems.push({
      type: 'navItem',
      text: `View ${values.textSingularName}s`,
      icon: 'eye',
      isFontAwesome: true,
      selected: this.state.selectedSection === 'all',
      onClick: () => {
        this.setState({ selectedSection: 'all' });
      },
    });

    if (Session.validateAccess(this.props.auth.site, values.permissionMaintenanceTypes, this.props.auth)) {
      sectionItems.push({
        type: 'navItem',
        text: values.textTitleJobTypes,
        // icon: 'maintenance2',
        // isSVG: true,
        selected: this.state.selectedSection === 'requestTypes',
        onClick: () => {
          this.setState({ selectedSection: 'requestTypes' });
        },
      });
    }

    if (Session.validateAccess(this.props.auth.site, 'featurePicker', this.props.auth)) {
      sectionItems.push({
        type: 'navItem',
        text: 'Feature Configuration',
        icon: 'settings',
        isFontAwesome: false,
        selected: this.state.selectedSection === 'config',
        onClick: () => {
          this.setState({ selectedSection: 'config' });
        },
      });
    }

    const helpGuide = values.hasHelpButton
      ? {
          text: `Help with ${values.textTitleRequests}`,
          url: values.helpGuideURL || Urls.HelpGuide.Maintenance,
        }
      : null;

    return (
      <Components.HubSidebar
        sections={[
          {
            title: this.props.strings[`${values.featureKey}_textTitleRequests`] || values.textTitleRequests,
            items: sectionItems,
          },
        ]}
        helpGuide={helpGuide}
      />
    );
  }

  renderRight() {
    if (this.state.selectedSection === 'requestTypes') {
      return <JobTypes onNew={this.onAddRequestType} />;
    } else if (this.state.selectedSection === 'config') {
      return <Configuration />;
    }
    return <JobList source={this.state.allList} />;
  }

  render() {
    return (
      <div className="hub-wrapperContainer">
        {this.renderLeftBar()}
        <div className="hub-headerContentWrapper">
          <Components.Header />
          <div className="hub-contentWrapper">{this.renderRight()}</div>
        </div>
      </div>
    );
  }
}

const styles = {
  sideBarTitleSection: {
    lineHeight: '40px',
    marginTop: 30,
    marginBottom: 30,
    paddingLeft: 24,
    paddingRight: 24,
  },
  sideBarSection: {
    weight: '100%',
    minWidth: 200,
    padding: 32,
    paddingLeft: 24,
    cursor: 'pointer',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
  },
  spinner: {
    fontSize: 32,
    color: Config.env.colourBrandingOff,
  },
};

const mapStateToProps = (state) => {
  const { auth } = state;
  return {
    jobs: state[values.reducerKey].jobs,
    auth,
    strings: (state.strings && state.strings.config) || {},
  };
};

export default connect(mapStateToProps, { jobsLoaded })(withRouter(RequestsHub));
