import React, { Component } from 'react';
import { Table } from 'react-bootstrap';
import { connect } from 'react-redux';
import _ from 'lodash';
import FontAwesome from 'react-fontawesome';
import { withRouter } from 'react-router';
import { Link } from 'react-router-dom';
import { jobTypesLoaded, jobTypesUpdate } from '../actions';
import { maintenanceActions } from '../apis';
import Config, { PlussCore } from '../feature.config';
import { values } from '../values.config';

const { Session, Components } = PlussCore;

class JobTypes extends Component {
  constructor(props) {
    super(props);
    this.state = {
      jobList: [],
      sortColumn: 'name',
      sortDesc: false,
      loading: true,
    };
  }

  componentWillMount() {
    this.updateProps(this.props);
    Session.checkLoggedIn(this, this.props.auth);
  }

  componentDidMount() {
    this.getJobTypes();
  }

  componentWillReceiveProps(nextProps) {
    this.updateProps(nextProps);
  }

  updateProps(props) {
    this.setState({ jobList: props.jobtypes });
  }

  getJobTypes = async () => {
    try {
      const res = await maintenanceActions.getJobTypes(this.props.auth.site);
      if (res.data != null) this.props.jobTypesLoaded(res.data);
    } catch (error) {
      console.error('getJobTypes', error);
    } finally {
      this.setState({ loading: false });
    }
  };

  sortByCol = (col) => {
    if (this.state.sortColumn === col) {
      this.setState({ sortDesc: !this.state.sortDesc });
    } else {
      this.setState({ sortColumn: col, sortDesc: false });
    }
  };

  onRemoveJobType = async (ev) => {
    if (!window.confirm(`Are you sure you want to delete ${ev.typeName}?`)) return;

    try {
      await maintenanceActions.deleteJobType(this.props.auth.site, ev.id);
      const index = _.findIndex(this.state.jobList, (job) => {
        return job != null && job.id === ev.id;
      });
      if (index > -1) {
        const newJobTypes = [...this.state.jobList];
        newJobTypes[index].Deleted = true;
        this.props.jobTypesLoaded(newJobTypes);
      }
    } catch (error) {
      console.error('onRemoveJobType', error);
      alert('Something went wrong with the request. Please try again.');
    }
  };

  renderList() {
    let source = _.sortBy(this.state.jobList, this.state.sortColumn);
    if (this.state.sortDesc) source.reverse();
    source = _.filter(source, (ev) => {
      if (!ev) return false;
      if (ev.Deleted) return false;
      return true;
    });

    return source.map((ev, index) => {
      if (ev != null) {
        return (
          <tr key={index}>
            <td className="table-TitleColumn">
              <Link to={`${values.routeAddRequestType}/${ev.id}`}>{ev.typeName}</Link>
            </td>
            <td>{ev.description}</td>
            <td>{ev.email}</td>
            <td className="table-options">
              <div style={{ display: 'flex', alignItems: 'center' }}>
                {Session.validateAccess(this.props.auth.site, values.permissionMaintenanceTypes, this.props.auth) && (
                  <Link to={`${values.routeAddRequestType}/${ev.id}`}>
                    <FontAwesome style={{ fontSize: 20, padding: 5, marginLeft: 12, cursor: 'pointer' }} name="pencil" />
                  </Link>
                )}
                {Session.validateAccess(this.props.auth.site, values.permissionMaintenanceTypes, this.props.auth) && (
                  <a onClick={() => this.onRemoveJobType(ev)}>
                    <FontAwesome style={{ fontSize: 20, padding: 5, marginLeft: 8, cursor: 'pointer' }} name="minus-circle" />
                  </a>
                )}
              </div>
            </td>
          </tr>
        );
      }
      return null;
    });
  }

  renderView() {
    return (
      <Table className="plussTable" striped bordered condensed hover style={{ minWidth: '100%' }}>
        <thead>
          <tr>
            <th style={{ cursor: 'pointer' }} onClick={() => this.sortByCol('name')}>
              {values.textSingularName} type
            </th>
            <th style={{ cursor: 'pointer' }} onClick={() => this.sortByCol('name')}>
              Type Description
            </th>
            <th style={{ cursor: 'pointer' }} onClick={() => this.sortByCol('email')}>
              Email
            </th>
            <th style={{ width: 70 }} />
          </tr>
        </thead>
        <tbody>{this.renderList()}</tbody>
      </Table>
    );
  }

  renderEmpty() {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', flex: 1, justifyContent: 'center', alignItems: 'center', marginTop: 32 }}>
        <div className="emptyState" />
        <div className="marginTop-32" style={{ maxWidth: 500, textAlign: 'center' }}>
          <span className="fontRegular fontSize-13">{values.textEmptyJobTypes}</span>
        </div>
        <div className="marginTop-8 fontRegular fontSize-13" style={{ maxWidth: 500, textAlign: 'center' }}>
          {values.textEmptyJobTypesExample}
        </div>
      </div>
    );
  }

  renderContent() {
    if (_.isEmpty(this.state.jobList)) return this.renderEmpty();
    return this.renderView();
  }

  renderJobTypes() {
    const { jobList, loading } = this.state;

    if (jobList.length === 0 && loading) {
      return (
        <div style={{ minWidth: '100%' }}>
          <div className="padding-60 paddingVertical-40" style={{ textAlign: 'center' }}>
            <FontAwesome style={{ fontSize: 30, color: Config.env.colourBrandingOff }} name="spinner fa-pulse fa-fw" />
          </div>
        </div>
      );
    }
    return (
      <div style={{ minWidth: '100%' }}>
        <div className="marginBottom-32">
          <Components.AddButton onClick={this.props.onNew} text={values.textNewTypeButton} />
        </div>
        {this.renderContent()}
      </div>
    );
  }

  render() {
    return (
      <div style={{ minWidth: '100%' }}>
        <div>{this.renderJobTypes()}</div>
        <div className="hub_tidioPadding"></div>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  const { auth } = state;
  return { jobtypes: state[values.reducerKey].jobtypes, auth };
};

export default connect(mapStateToProps, { jobTypesLoaded, jobTypesUpdate })(withRouter(JobTypes));
