import React, { Component } from 'react';
import { Table } from 'react-bootstrap';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { Link } from 'react-router-dom';
import FontAwesome from 'react-fontawesome';
import moment from 'moment';
import _ from 'lodash';
import { jobsLoaded, removeJob, jobStatusesUpdate } from '../actions';
import { PlussCore } from '../feature.config';
import { maintenanceActions } from '../apis';
import {
  STATUS_NOT_ACTIONED,
  STATUS_COMPLETED,
  STATUS_IMCOMPLETE,
  jobPriorityOptions,
  getDefaultPriority,
  getJobPriority,
} from '../helper';
import { Colours } from '@plusscommunities/pluss-core-web';
import { values } from '../values.config';

const { Session, Components, Analytics } = PlussCore;

class JobList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showCompleted: false,
      sortColumn: 'createdUnix',
      sortDesc: true,
      selectedTimeFilter: Analytics.getAnalyticsFilterOptions()[1],
      assignees: [],
      requesters: [],
    };

    this.exportColumns = [
      { label: 'Select All', key: '' },
      { label: 'System Id', key: 'id' },
      { label: `${values.textEntityName} No.`, key: 'jobId' },
      { label: values.textJobType, key: 'type' },
      { label: 'Status', key: 'status' },
      { label: 'Priority', key: 'priority' },
      { label: 'Title', key: 'title' },
      { label: 'Address', key: 'room' },
      { label: 'Description', key: 'description' },
      { label: 'Notes', key: 'notes' },
      { label: 'User Name', key: 'userName' },
      { label: 'User ID', key: 'userID' },
      { label: 'Request Time', key: 'createdTime' },
      { label: 'Progress Time', key: 'progressTime' },
      { label: 'Completed Time', key: 'completedTime' },
      { label: 'Time to Progress (in seconds)', key: 'progressDuration' },
      { label: 'Time to Complete (in seconds)', key: 'completedDuration' },
    ];
  }

  UNSAFE_componentWillMount() {
    Session.checkLoggedIn(this);
  }

  componentDidMount() {
    this.props.jobStatusesUpdate(this.props.auth.site);
    this.getJobs();
    this.getAssignees();
  }

  setRequesters = (jobs) => {
    const requesters = _.orderBy(
      _.uniqBy(
        jobs.map((j) => ({
          id: j.userID,
          displayName: j.userName,
          profilePic: j.userProfilePic,
        })),
        'id',
      ),
      'displayName',
      'asc',
    );
    this.setState({ requesters });
  };

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

  getAssignees = async () => {
    try {
      const res = await maintenanceActions.getAssignees(this.props.auth.site);
      this.setState({ assignees: res.data.Users });
    } catch (error) {
      console.error('getAssignees', error);
    }
  };

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

  onRemoveRequest = async (request) => {
    if (window.confirm(values.textAreYouSureYouWantToDelete)) {
      this.props.removeJob(request.id);
      try {
        await maintenanceActions.deleteJob(this.props.auth.site, request.id);
        this.getJobs();
      } catch (error) {
        console.log('onRemoveRequest', error);
        alert('Something went wrong with the request. Please try again.');
      }
    }
  };

  openFilter = (filter) => {
    this.setState({
      filterOpen: filter,
    });
  };

  closeFilter = () => {
    this.setState({
      filterOpen: null,
    });
  };

  selectTypeFilter = (filter) => {
    this.setState({
      selectedTypeFilter: filter,
    });
    this.closeFilter();
  };

  selectPriorityFilter = (filter) => {
    this.setState({
      selectedPriorityFilter: filter,
    });
    this.closeFilter();
  };

  selectStatusFilter = (filter) => {
    this.setState({
      selectedStatusFilter: filter,
    });
    this.closeFilter();
  };

  timeFilterChanged = (selectedTimeFilter) => {
    this.setState({ selectedTimeFilter });
  };

  timeFilterDateRangeChanged = (startDate, endDate) => {
    this.setState({ timeFilterStart: startDate, timeFilterEnd: endDate });
  };

  isValidTimeFilter = () => {
    if (!this.state.selectedTimeFilter) {
      return false;
    }
    if (this.state.selectedTimeFilter.dayCount > 0) {
      return true;
    }
    return moment(this.state.timeFilterStart).startOf('d').valueOf() < moment(this.state.timeFilterEnd).endOf('d').valueOf();
  };

  saveTimeFilter = () => {
    if (!this.isValidTimeFilter()) {
      return;
    }
    let startTime = 0;
    let endTime = moment().endOf('d').valueOf();
    let text = '';
    if (this.state.selectedTimeFilter.dayCount > 0) {
      startTime = moment().add(-this.state.selectedTimeFilter.dayCount, 'd').startOf('d').valueOf();
      text = this.state.selectedTimeFilter.text;
    } else {
      const startDate = moment(this.state.timeFilterStart).startOf('d');
      const endDate = moment(this.state.timeFilterEnd).endOf('d');
      startTime = startDate.valueOf();
      endTime = endDate.valueOf();
      text = `${startDate.format('DD/MM/YYYY')}  to  ${endDate.format('DD/MM/YYYY')}`;
    }
    this.setState({
      selectedTimeFilterStart: startTime,
      selectedTimeFilterEnd: endTime,
      selectedTimeFilterText: text,
    });
    this.closeFilter();
  };

  removeTimeFilter = () => {
    this.setState({
      selectedTimeFilterStart: null,
      selectedTimeFilterEnd: null,
      selectedTimeFilterText: null,
    });
  };

  onHandleChange = (event) => {
    var stateChange = {};
    stateChange[event.target.getAttribute('id')] = event.target.value;
    this.setState(stateChange);
  };

  onSelectAssignee = (user) => {
    this.setState({
      selectedAssignee: user,
    });
  };

  removeUserFilter = () => {
    this.setState({
      selectedUserFilter: null,
      selectedUserFilterText: null,
    });
  };

  saveUserFilter = () => {
    if (!this.state.selectedAssignee) {
      this.removeUserFilter();
    } else {
      this.setState({
        selectedUserFilter: this.state.selectedAssignee.id,
        selectedUserFilterText: this.state.selectedAssignee.displayName,
        selectedAssignee: null,
      });
    }
    this.closeFilter();
  };

  onSelectRequester = (user) => {
    this.setState({
      selectedRequester: user,
    });
  };

  removeRequesterFilter = () => {
    this.setState({
      selectedRequesterFilter: null,
      selectedRequesterFilterText: null,
    });
  };

  saveRequesterFilter = () => {
    if (!this.state.selectedRequester) {
      this.removeRequesterFilter();
    } else {
      this.setState({
        selectedRequesterFilter: this.state.selectedRequester.id,
        selectedRequesterFilterText: this.state.selectedRequester.displayName,
        selectedRequester: null,
      });
    }
    this.closeFilter();
  };

  onHandleSearchChange = (event) => {
    const thisSearchTime = moment().valueOf();
    this.setState({ search: event.target.value, lastSearch: thisSearchTime });

    setTimeout(() => {
      // delayed setter to avoid filtering on every keypress
      if (this.state.lastSearch === thisSearchTime) {
        this.setState({
          searchTerm: this.state.search,
        });
      }
    }, 500);
  };

  getSource = () => {
    let source = this.props.source;

    // filter by time
    if (this.state.selectedTimeFilterStart && this.state.selectedTimeFilterEnd) {
      source = _.filter(source, (r) => {
        return r.createdUnix >= this.state.selectedTimeFilterStart && r.createdUnix <= this.state.selectedTimeFilterEnd;
      });
    }

    // filter by type
    if (this.state.selectedTypeFilter) {
      source = _.filter(source, (r) => {
        return r.type === this.state.selectedTypeFilter;
      });
    }

    // filter by priority
    if (this.state.selectedPriorityFilter) {
      const defaultPriority = getDefaultPriority().name;
      source = _.filter(source, (r) => {
        return (
          r.priority === this.state.selectedPriorityFilter || (this.state.selectedPriorityFilter === defaultPriority && _.isNil(r.priority))
        );
      });
    }

    // filter by status
    if (this.state.selectedStatusFilter) {
      const { statusTypes } = this.props;
      const defaultStatus = statusTypes.find((s) => s.category === STATUS_NOT_ACTIONED);
      source = _.filter(source, (r) => {
        const status = statusTypes.find((s) => s.text === r.status) || defaultStatus;
        if (this.state.selectedStatusFilter === STATUS_IMCOMPLETE) {
          return status.category !== STATUS_COMPLETED;
        }
        return status.text === this.state.selectedStatusFilter;
      });
    }

    if (this.state.selectedUserFilter) {
      source = _.filter(source, (r) => {
        return r.AssigneeId === this.state.selectedUserFilter;
      });
    }

    if (this.state.selectedRequesterFilter) {
      source = _.filter(source, (r) => {
        return r.userID === this.state.selectedRequesterFilter;
      });
    }

    if (!_.isEmpty(this.state.searchTerm)) {
      source = _.filter(source, (r) => {
        if (r.jobId && r.jobId === this.state.searchTerm) {
          return true;
        }
        if (r.room && r.room.toLowerCase().indexOf(this.state.searchTerm.toLowerCase()) > -1) {
          return true;
        }
        if (r.title && r.title.toLowerCase().indexOf(this.state.searchTerm.toLowerCase()) > -1) {
          return true;
        }
        return false;
      });
    }

    source = _.sortBy(source, (event) => {
      if (this.state.sortColumn === 'assigned') {
        return event.Assignee ? event.Assignee.displayName : 'Unassigned';
      }
      if (this.state.sortColumn !== 'createdUnix') return event[this.state.sortColumn];
      return event.createdUnix;
    });
    if (this.state.sortDesc) source.reverse();
    return source;
  };

  getCustomFieldValue = (field) => {
    switch (field.type) {
      case 'date':
        return field.answer ? moment(field.answer, 'YYYY-MM-DD').format('DD-MMM-YYYY') : '';
      case 'time':
        return field.answer ? moment(field.answer, 'HH:mm').format('h:mm a') : '';
      case 'yn':
        return field.answer ? 'Yes' : 'No';
      case 'checkbox':
        return field.answer && Array.isArray(field.answer) ? field.answer.join(', ') : '';
      default:
        return field.answer;
    }
  };

  getCustomFields = (job, customColumns) => {
    const { customFields, type } = job;
    const customValues = {};
    if (customFields && Array.isArray(customFields)) {
      customFields.forEach((field) => {
        // Exclude un-exportable fields
        if (['image', 'staticTitle', 'staticText'].includes(field.type)) return;

        const fieldKey = `${_.camelCase(type)}.${_.camelCase(field.label)}`;
        // Build custom columns
        const exists = customColumns.find((c) => c.key === fieldKey);
        if (!exists) {
          customColumns.push({ label: field.label, key: fieldKey });
        }
        // Build custom field source
        customValues[fieldKey] = this.getCustomFieldValue(field);
      });
    }
    return customValues;
  };

  getExportSource = () => {
    const customColumns = [];
    const defaultPriority = getDefaultPriority().name;
    const source = this.getSource().map((r) => {
      const history = r.history || [];
      const progressEntry = _.find(history, (e) => {
        return e.status !== 'Unassigned';
      });
      const completedEntry = _.find(history, (e) => {
        return e.status === 'Completed';
      });
      let progressTime = null;
      let completedTime = null;
      let progressDuration = null;
      let completedDuration = null;
      if (progressEntry) {
        progressTime = moment.utc(progressEntry.timestamp).format();
        progressDuration = moment.utc(progressEntry.timestamp).unix() - moment.utc(r.createdTime).unix();
      }
      if (completedEntry) {
        completedTime = moment.utc(completedEntry.timestamp).format();
        completedDuration = moment.utc(completedEntry.timestamp).unix() - moment.utc(r.createdTime).unix();
      }
      let notes = '';
      (r.Notes || []).forEach((note, index) => {
        if (index > 0) {
          notes += '\n\n';
        }
        if (note.User && !_.isEmpty(note.User.displayName)) {
          notes += `${note.User.displayName}:\n`;
        }
        if (note.Timestamp) {
          notes += `${moment(note.Timestamp).format('DD-MM-YYYY h:mma')}\n`;
        }
        notes += note.Note;
      });
      const customFieldValues = this.getCustomFields(r, customColumns);
      const priority = r.priority || defaultPriority;
      return { ...r, ...customFieldValues, notes, progressTime, completedTime, progressDuration, completedDuration, priority };
    });

    // Compose revised columns list with custom fields
    const index = this.exportColumns.findIndex((c) => c.key === 'notes');
    const columns = [...this.exportColumns.slice(0, index), ...customColumns, ...this.exportColumns.slice(index)];
    return { columns, source };
  };

  isExportReady = () => {
    return !_.isEmpty(this.getSource());
  };

  onOpenExportCsv = () => {
    if (!this.isExportReady()) return;
    this.setState({ exportCsvOpen: true });
  };

  onCloseExportCsv = () => {
    this.setState({ exportCsvOpen: false });
  };

  renderFilterPopup() {
    if (!this.state.filterOpen) {
      return null;
    }
    if (this.state.filterOpen === 'type') {
      return (
        <Components.Popup title={`Select ${values.textJobType}`} maxWidth={600} minWidth={400} hasPadding onClose={this.closeFilter}>
          {_.sortBy(_.uniq(this.props.source.map((r) => r.type)), (t) => t.toLowerCase()).map((type) => {
            return (
              <Components.Tag
                key={type}
                onClick={() => {
                  this.selectTypeFilter(type);
                }}
                text={type}
                className="marginRight-10"
              />
            );
          })}
        </Components.Popup>
      );
    }
    if (this.state.filterOpen === 'priority') {
      return (
        <Components.Popup title="Select Priority" maxWidth={600} minWidth={400} hasPadding onClose={this.closeFilter}>
          {jobPriorityOptions.map((p) => {
            return (
              <Components.Tag
                key={p.name}
                onClick={() => {
                  this.selectPriorityFilter(p.name);
                }}
                text={p.name}
                className="marginRight-10"
              />
            );
          })}
        </Components.Popup>
      );
    }
    if (this.state.filterOpen === 'status') {
      const { statusTypes } = this.props;
      return (
        <Components.Popup title="Select Status" maxWidth={600} minWidth={400} hasPadding onClose={this.closeFilter}>
          {[STATUS_IMCOMPLETE, ...statusTypes.map((s) => s.text)].map((status) => {
            return (
              <Components.Tag
                key={status}
                onClick={() => {
                  this.selectStatusFilter(status);
                }}
                text={status}
                className="marginRight-10 marginBottom-10"
              />
            );
          })}
        </Components.Popup>
      );
    }
    if (this.state.filterOpen === 'time') {
      return (
        <Components.Popup
          title="Select Time"
          maxWidth={600}
          minWidth={400}
          hasPadding
          onClose={this.closeFilter}
          buttons={[
            {
              type: 'primaryAction',
              onClick: this.saveTimeFilter,
              text: 'Select',
              isActive: this.isValidTimeFilter(),
            },
          ]}
        >
          <div style={{ minHeight: 150 }}>
            <Components.AnalyticsFilter
              defaultFilter={this.state.selectedTimeFilter}
              filterChanged={this.timeFilterChanged}
              filterDateRangeChanged={this.timeFilterDateRangeChanged}
            />
          </div>
        </Components.Popup>
      );
    }
    if (this.state.filterOpen === 'user') {
      let userContent = null;
      if (this.state.selectedAssignee) {
        userContent = (
          <div>
            <Components.UserListing
              key={this.state.selectedAssignee.id}
              user={this.state.selectedAssignee}
              rightContent={
                <Components.SVGIcon
                  className="removeIcon"
                  icon="close"
                  onClick={() => {
                    this.onSelectAssignee();
                  }}
                  colour={Colours.COLOUR_DUSK}
                />
              }
            />
          </div>
        );
      } else {
        userContent = (
          <div>
            <Components.GenericInput
              id="userSearch"
              type="text"
              // label="Search"
              placeholder="Search name"
              value={this.state.userSearch}
              onChange={(e) => this.onHandleChange(e)}
              alwaysShowLabel
            />
            {_.sortBy(this.state.assignees, (u) => u.displayName.toUpperCase())
              .filter((u) => {
                if (_.isEmpty(this.state.userSearch)) return true;
                return u.displayName.toUpperCase().indexOf(this.state.userSearch.toUpperCase()) > -1;
              })
              .map((user) => {
                return (
                  <Components.UserListing
                    key={user.id}
                    user={user}
                    onClick={() => {
                      this.onSelectAssignee(user);
                    }}
                  />
                );
              })}
          </div>
        );
      }
      return (
        <Components.Popup
          title="Select User"
          maxWidth={600}
          minWidth={400}
          hasPadding
          onClose={this.closeFilter}
          buttons={[
            {
              type: 'primaryAction',
              onClick: this.saveUserFilter,
              text: 'Select',
              isActive: true,
            },
          ]}
        >
          {userContent}
        </Components.Popup>
      );
    }
    if (this.state.filterOpen === 'requester') {
      let userContent = null;
      if (this.state.selectedRequester) {
        userContent = (
          <div>
            <Components.UserListing
              key={this.state.selectedRequester.id}
              user={this.state.selectedRequester}
              rightContent={
                <Components.SVGIcon
                  className="removeIcon"
                  icon="close"
                  onClick={() => {
                    this.onSelectRequester();
                  }}
                  colour={Colours.COLOUR_DUSK}
                />
              }
            />
          </div>
        );
      } else {
        userContent = (
          <div>
            <Components.GenericInput
              id="requesterSearch"
              type="text"
              // label="Search"
              placeholder="Search name"
              value={this.state.requesterSearch}
              onChange={(e) => this.onHandleChange(e)}
              alwaysShowLabel
            />
            {_.sortBy(this.state.requesters, (u) => u.displayName.toUpperCase())
              .filter((u) => {
                if (_.isEmpty(this.state.requesterSearch)) return true;
                return u.displayName.toUpperCase().indexOf(this.state.requesterSearch.toUpperCase()) > -1;
              })
              .map((user) => {
                return (
                  <Components.UserListing
                    key={user.id}
                    user={user}
                    onClick={() => {
                      this.onSelectRequester(user);
                    }}
                  />
                );
              })}
          </div>
        );
      }
      return (
        <Components.Popup
          title="Select User"
          maxWidth={600}
          minWidth={400}
          hasPadding
          onClose={this.closeFilter}
          buttons={[
            {
              type: 'primaryAction',
              onClick: this.saveRequesterFilter,
              text: 'Select',
              isActive: true,
            },
          ]}
        >
          {userContent}
        </Components.Popup>
      );
    }
    return null;
  }

  renderRequests() {
    const { statusTypes } = this.props;
    const defaultStatus = statusTypes.find((s) => s.category === STATUS_NOT_ACTIONED);

    return this.getSource().map((ev, index) => {
      if (!ev) {
        return null;
      }
      const status = (ev.status && statusTypes.find((s) => s.text === ev.status)) || defaultStatus;
      const priority = getJobPriority(ev.priority);

      return (
        <tr key={index}>
          <td>{ev.jobId}</td>
          <td className="table-TitleColumn">
            <Link to={`${values.routeRequestDetails}/${ev.id}`}>
              <span>{ev.title}</span>
            </Link>
          </td>
          <td>{ev.type}</td>
          <td>{moment.utc(ev.createdTime).local().format('D MMM YY')}</td>
          <td>{ev.room}</td>
          <td>
            {ev.userName ? (
              <Components.UserListing
                user={{ id: ev.userID, displayName: ev.userName, profilePic: ev.userProfilePic }}
                textClass="fontSize-13"
              />
            ) : (
              'Unknown'
            )}
          </td>
          <td>{ev.Assignee ? <Components.UserListing user={ev.Assignee} textClass="fontSize-13" /> : 'Unassigned'}</td>
          {/* <td>
        <div style={{ textAlign: 'center' }}>{ev.commentCount}</div>
          </td> */}
          <td>
            <div
              style={{
                textAlign: 'center',
                borderRadius: 4,
                width: 100,
                paddingTop: 2,
                paddingBottom: 2,
                color: '#fff',
                backgroundColor: status ? status.color : undefined,
              }}
            >
              {status ? status.text : ''}
            </div>
          </td>
          <td>
            <div
              style={{
                textAlign: 'center',
                borderRadius: 4,
                width: 100,
                paddingTop: 2,
                paddingBottom: 2,
                color: '#fff',
                backgroundColor: priority.color,
              }}
            >
              {priority.name}
            </div>
          </td>
          <td className="table-options">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Link to={`${values.routeRequestDetails}/${ev.id}`}>
                <FontAwesome style={{ fontSize: 20, padding: 5, cursor: 'pointer' }} name="pencil" />
              </Link>
              {Session.validateAccess(this.props.auth.site, values.permissionMaintenanceTracking, this.props.auth) && (
                <a onClick={() => this.onRemoveRequest(ev)}>
                  <FontAwesome style={{ fontSize: 20, padding: 5, marginLeft: 8, cursor: 'pointer' }} name="minus-circle" />
                </a>
              )}
            </div>
          </td>
        </tr>
      );
    });
  }

  renderSort(col) {
    const { sortColumn, sortDesc } = this.state;
    if (col !== sortColumn) return null;
    return <FontAwesome style={{ marginLeft: 5 }} name={sortDesc ? 'chevron-up' : 'chevron-down'} />;
  }

  sortIsActive(col) {
    if (col !== this.state.sortColumn) return '';
    return ' table--columnActive';
  }

  renderEmpty() {
    const title = this.props.strings[`${values.featureKey}_textTitleRequests`] || values.textTitleRequests;

    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">
            <span className="fontHeavy text-brandingColour">{title} </span>
            {values.textEmptyDescription}
          </span>
        </div>
        <div className="marginTop-8 fontRegular fontSize-13" style={{ maxWidth: 500, textAlign: 'center' }}>
          {values.textEmptyExample}
        </div>
      </div>
    );
  }

  renderContent() {
    if (_.isEmpty(this.props.source)) return this.renderEmpty();

    return (
      <Table className="plussTable" striped bordered condensed hover style={{ minWidth: '100%' }}>
        <thead>
          <tr>
            <th
              className={`${this.sortIsActive('jobId')}`}
              style={{ cursor: 'pointer', width: 70 }}
              onClick={() => {
                this.sortByCol('jobId');
              }}
            >
              {values.textEntityName} No.{this.renderSort('jobId')}
            </th>
            <th
              className={`${this.sortIsActive('title')}`}
              style={{ cursor: 'pointer' }}
              onClick={() => {
                this.sortByCol('title');
              }}
            >
              Title{this.renderSort('title')}
            </th>
            <th
              className={`${this.sortIsActive('type')}`}
              style={{ cursor: 'pointer', width: 100 }}
              onClick={() => {
                this.sortByCol('type');
              }}
            >
              {values.textJobType}
              {this.renderSort('type')}
            </th>
            <th
              className={`${this.sortIsActive('createdUnix')}`}
              style={{ cursor: 'pointer', width: 80 }}
              onClick={() => {
                this.sortByCol('createdUnix');
              }}
            >
              Date{this.renderSort('createdUnix')}
            </th>
            <th
              className={`${this.sortIsActive('room')}`}
              style={{ cursor: 'pointer', width: 100 }}
              onClick={() => {
                this.sortByCol('room');
              }}
            >
              Address{this.renderSort('room')}
            </th>
            <th
              className={`${this.sortIsActive('userName')}`}
              style={{ cursor: 'pointer', width: 150 }}
              onClick={() => {
                this.sortByCol('userName');
              }}
            >
              Submitted By{this.renderSort('userName')}
            </th>
            <th
              className={`${this.sortIsActive('assigned')}`}
              style={{ cursor: 'pointer', width: 150 }}
              onClick={() => {
                this.sortByCol('assigned');
              }}
            >
              Assigned To{this.renderSort('assigned')}
            </th>
            {/* <th style={{ width: 30 }}>Comments</th> */}
            <th style={{ width: 120 }}>Status</th>
            <th style={{ width: 120 }}>Priority</th>
            <th style={{ width: 50 }} />
          </tr>
        </thead>
        <tbody>{this.renderRequests()}</tbody>
      </Table>
    );
  }

  renderFilters() {
    let typeFilter = (
      <Components.Tag
        className="marginRight-10"
        onClick={() => {
          this.openFilter('type');
        }}
        text={values.textJobType}
      />
    );
    let statusFilter = (
      <Components.Tag
        className="marginRight-10"
        onClick={() => {
          this.openFilter('status');
        }}
        text="Status"
      />
    );
    let priorityFilter = (
      <Components.Tag
        className="marginRight-10"
        onClick={() => {
          this.openFilter('priority');
        }}
        text="Priority"
      />
    );
    let timeFilter = (
      <Components.Tag
        className="marginRight-10"
        onClick={() => {
          this.openFilter('time');
        }}
        text="Time"
      />
    );
    let userFilter = (
      <Components.Tag
        className="marginRight-10"
        onClick={() => {
          this.openFilter('user');
        }}
        text="Assigned To"
      />
    );
    let requesterFilter = (
      <Components.Tag
        className="marginRight-10"
        onClick={() => {
          this.openFilter('requester');
        }}
        text="Submitted By"
      />
    );

    if (this.state.selectedTypeFilter) {
      typeFilter = (
        <Components.Tag
          className="marginRight-10"
          onClick={() => {
            this.openFilter('type');
          }}
          rightIcon="close"
          rightClick={(e) => {
            e.stopPropagation();
            this.selectTypeFilter();
          }}
          text={this.state.selectedTypeFilter}
        />
      );
    }

    if (this.state.selectedPriorityFilter) {
      priorityFilter = (
        <Components.Tag
          className="marginRight-10"
          onClick={() => {
            this.openFilter('priority');
          }}
          rightIcon="close"
          rightClick={(e) => {
            e.stopPropagation();
            this.selectPriorityFilter();
          }}
          text={this.state.selectedPriorityFilter}
        />
      );
    }

    if (this.state.selectedStatusFilter) {
      statusFilter = (
        <Components.Tag
          className="marginRight-10"
          onClick={() => {
            this.openFilter('status');
          }}
          rightIcon="close"
          rightClick={(e) => {
            e.stopPropagation();
            this.selectStatusFilter();
          }}
          text={this.state.selectedStatusFilter}
        />
      );
    }
    if (this.state.selectedTimeFilterText) {
      timeFilter = (
        <Components.Tag
          className="marginRight-10"
          onClick={() => {
            this.openFilter('time');
          }}
          rightIcon="close"
          rightClick={(e) => {
            e.stopPropagation();
            this.removeTimeFilter();
          }}
          text={this.state.selectedTimeFilterText}
        />
      );
    }
    if (this.state.selectedUserFilter) {
      userFilter = (
        <Components.Tag
          className="marginRight-10"
          onClick={() => {
            this.openFilter('user');
          }}
          rightIcon="close"
          rightClick={(e) => {
            e.stopPropagation();
            this.removeUserFilter();
          }}
          text={this.state.selectedUserFilterText}
        />
      );
    }
    if (this.state.selectedRequesterFilter) {
      requesterFilter = (
        <Components.Tag
          className="marginRight-10"
          onClick={() => {
            this.openFilter('requester');
          }}
          rightIcon="close"
          rightClick={(e) => {
            e.stopPropagation();
            this.removeRequesterFilter();
          }}
          text={this.state.selectedRequesterFilterText}
        />
      );
    }
    return (
      <div>
        <div className="marginTop-20 flex flex-between flex-center">
          <div className="flex flex-center">
            <Components.Text type="h5" className="marginRight-20">
              Filter by
            </Components.Text>
            {typeFilter}
            {statusFilter}
            {priorityFilter}
            {timeFilter}
            {userFilter}
            {requesterFilter}
          </div>
          <Components.Button
            inline
            buttonType="primaryAction"
            leftIcon="file-code-o"
            onClick={this.onOpenExportCsv}
            isActive={!_.isEmpty(this.getSource())}
          >
            Export CSV
          </Components.Button>
        </div>
        <Components.GenericInput
          id="search"
          type="text"
          placeholder={`Search by ${values.textEntityName} ID, Address or Title`}
          value={this.state.search}
          onChange={(e) => this.onHandleSearchChange(e)}
          className="genericInputContainer-rounded marginTop-10"
          style={{ maxWidth: 500 }}
        />
      </div>
    );
  }

  renderCSVPopup() {
    if (!this.state.exportCsvOpen) {
      return null;
    }

    const { columns, source } = this.getExportSource();
    return <Components.ExportCsvPopup onClose={this.onCloseExportCsv} columns={columns} source={source} filename="requests.csv" />;
  }

  render() {
    return (
      <div style={{ minWidth: '100%' }}>
        {this.renderFilterPopup()}
        {this.renderCSVPopup()}
        {this.renderFilters()}
        {this.renderContent()}
      </div>
    );
  }
}

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

export default connect(mapStateToProps, { jobsLoaded, removeJob, jobStatusesUpdate })(withRouter(JobList));
