import *  as React from "react";
import ReactTable from "react-table";
import selectTableHOC from "react-table/lib/hoc/selectTable";
import * as moment from "moment";

import "react-table/react-table.css";
const filterIcon = require('../assets/filter.svg');
const sortIcon = require('../assets/noun_sorting_1058866.svg');
const confirmIcon = require('../assets/noun_confirm_275573.svg');

import Pagination from "./Pagination";
import "./style.css";

// react select table
const SelectTable = selectTableHOC(ReactTable);

export interface TableContentProps {
  headerProps,
  rowsData,
  isLoading: boolean,
  sortDirection: string,
  sortBy,
  handleSorting,
  filterData: Function
}

export default class TableContent extends React.Component<TableContentProps, {}> {
  private inputRef = null;
  private checkboxTable = null;

  state = {
    filter: {
      key: "",
      value: "",
      obj: "",
      type: ""
    },
    selectAll: false,
    selection: [],
  };

  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  escFunction = event => {
    if (event.keyCode === 27) {
      this.setState({
        filter: {
          key: "",
          value: "",
          obj: {},
          type: ""
        }
      });
    }
  };

  componentDidMount() {
    document.addEventListener("keydown", this.escFunction, false);
  }

  componentWillUnmount() {
    document.removeEventListener("keydown", this.escFunction, false);
  }

  handleKeyFilter = col => {
    this.setState({
      filter: {
        key: col.name,
        value: "",
        obj: {},
        type: col.type
      }
    });
  };

  createFilterObj = () => {
    let obj;
    if (this.state.filter.value) {
      if (this.state.filter.type === "Timestamp") {
        let value;
        switch (this.state.filter.value) {
          case "last_day":
            value = moment().subtract(1, "days");
            break;
          case "last_week":
            value = moment().subtract(7, "days");
            break;
          case "last_month":
            value = moment().subtract(30, "days");
            break;
          case "last_year":
            value = moment().subtract(365, "days");
            break;
          default:
            value = moment();
        }
        obj = {
          key: this.state.filter.key,
          value: { $gt: value }
        };
      } else {
        obj = {
          key: this.state.filter.key,
          value: this.state.filter.value
        };
      }
      this.props.filterData(obj);
    }
    this.setState({
      filter: {
        key: "",
        value: "",
        obj: "",
        type: ""
      }
    });
  };

  handleFilterValueChange = e => {
    const value = e.target.value;
    this.setState((prevState: any) => ({ filter: { ...prevState.filter, value: value } }),
      () => {
        this.inputRef.current.focus();
      }
    );
  };

  handleSelect = e => {
    const value = e.target.value;
    this.setState((prevState: any) => ({
      filter: { ...prevState.filter, value: value }
    }));
  };

  toggleSelection = (key, shift, row) => {
    // start off with the existing state
    let selection = [...this.state.selection];
    const keyIndex = selection.indexOf(key);
    // check to see if the key exists
    if (keyIndex >= 0) {
      // it does exist so we will remove it using destructing
      selection = [
        ...selection.slice(0, keyIndex),
        ...selection.slice(keyIndex + 1)
      ];
    } else {
      // it does not exist so add it
      selection.push(key);
    }
    // update the state
    this.setState({ selection });
  };

  toggleAll = () => {
    const selectAll = !this.state.selectAll;
    const selection = [];

    if (selectAll) {
      // we need to get at the internals of ReactTable
      const wrappedInstance = this.checkboxTable.getWrappedInstance();
      // the 'sortedData' property contains the currently accessible records based on the filter and sort
      const currentRecords = wrappedInstance.getResolvedState().sortedData;
      // we just push all the IDs onto the selection array
      currentRecords.forEach(item => {
        selection.push(`select-${item._original._id}`);
      });
    }
    this.setState({ selectAll, selection });
  };

  isSelected = key => {
    return this.state.selection.includes(`select-${key}`);
  };

  renderColumns = () => {
    const { filter } = this.state;
    const { sortDirection, sortBy, handleSorting } = this.props;
    let columns = [];
    this.props.headerProps.map((col: any, idx) => {
      const lastIndex = this.props.headerProps.length - 1;
      const obj = {
        Header: props => {
          return (
            <div className="fe-audits-time-filter">
              <span
                onClick={() =>
                  col.sortable
                    ? handleSorting(
                      col.name,
                      sortBy === col.name ? sortDirection : "desc"
                    )
                    : {}
                }>
                {col.displayName}
                {col.sortable && (
                  <img
                    src={sortIcon}
                    alt="sort"
                    className="fe-audits-filter-icon"
                  />
                )}
              </span>
              {col.filterable && (
                <a onClick={() => this.handleKeyFilter(col)}>
                  <img
                    src={filterIcon}
                    alt="filter"
                    width={10}
                    height={10}
                    className="fe-audits-filter-icon"
                  />
                </a>
              )}
              {col.name === filter.key
                ? [
                  <div
                    key={0}
                    id="modal-backdrop"
                    className="fe-audits-modal-backdrop-transparent fe-audits-modal-transition"
                    onClick={() => this.handleKeyFilter("")}
                  />,
                  <div
                    key={1}
                    className={`fe-audits-time-filter-div ${
                      idx === lastIndex ? "fe-audits-last-filter" : ""
                      }`}>
                    <h5 className="fe-audits-filter-user-text">
                      Filter By {col.displayName}
                    </h5>
                    <form onSubmit={() => this.createFilterObj()}>
                      <div className="fe-audits-filter-input">
                        {col.name === "severity" ? (
                          <select
                            className="fe-audits-filter-select"
                            value={this.state.filter.value || "select"}
                            onChange={e => this.handleSelect(e)}>
                            <option disabled value="select">
                              select severity
                              </option>
                            <option value="Info">Info</option>
                            <option value="Medium">Medium</option>
                            <option value="High">High</option>
                            <option value="Critical">Critical</option>
                          </select>
                        ) : col.type === "Timestamp" ? (
                          <select
                            className="fe-audits-filter-select"
                            value={this.state.filter.value || "select"}
                            onChange={e => this.handleSelect(e)}>
                            <option disabled value="select">
                              Select Time
                              </option>
                            <option value="last_day">Last Day</option>
                            <option value="last_week">Last Week</option>
                            <option value="last_month">Last Month</option>
                            <option value="last_year">Last Year</option>
                          </select>
                        ) : (
                              <input
                                ref={this.inputRef}
                                type={`${
                                  col.type === "Timestamp" ? "date" : "text"
                                  }`}
                                placeholder={`Search ${col.displayName}`}
                                key={col._id}
                                className="fe-audits-filter-user-input"
                                name={col.name}
                                value={
                                  filter.value ||
                                  (col.type === "Timestamp"
                                    ? moment().format("YYYY-MM-DD")
                                    : "")
                                }
                                onChange={e => this.handleFilterValueChange(e)}
                              />
                            )}
                        <div
                          className="fe-audits-confirm-btn"
                          onClick={() => this.createFilterObj()}>
                          <img width="15px" src={confirmIcon} alt="confirm" />
                        </div>
                      </div>
                    </form>
                  </div>
                ]
                : null}
            </div>
          );
        },
        headerClassName: `${
          sortBy === col.name
            ? sortDirection === "desc"
              ? "-sort-desc"
              : "-sort-asc"
            : ""
          }`,
        accessor: col.name,
        sortable: false,
        Cell: rowProps => {
          switch (col.name) {
            case "createdAt":
              return (
                <div>
                  <span className="fe-audits-name">
                    {rowProps.row[col.name] &&
                      moment(rowProps.row[col.name]).format(
                        "DD/MM/YYYY hh:mm:ss"
                      )}
                  </span>
                  <br />
                  <span className="fe-audits-time-status">
                    {rowProps.row[col.name] &&
                      moment(rowProps.row[col.name]).fromNow()}
                  </span>
                </div>
              );
            case "severity":
              return (
                <div
                  className={`fe-audits-severity-div fe-audits-${rowProps.row[
                    col.name
                  ].toLowerCase()}`}>
                  <span className={`fe-audits-severity-text`}>
                    {rowProps.row[col.name]}
                  </span>
                  <div
                    className={`fe-audits-severity-inner-div fe-audits-${rowProps.row[
                      col.name
                    ].toLowerCase()}`}
                  />
                </div>
              );
            default:
              return (
                <div>
                  <span className="fe-audits-name">
                    {rowProps.row[col.name]}
                  </span>
                </div>
              );
          }
        },
        headerStyle: {
          backgroundColor: "white",
          border: "0",
          borderBottom: "1px solid rgb(221, 221, 221)",
          textAlign: "start",
          minHeight: "40px",
          padding: "10px"
        },
        style: { backgroundColor: "white", padding: "10px", border: "0" },
        className: "fe-audits-cell-center"
      };
      columns.push(obj);
    });
    return columns;
  };

  render() {
    const data = this.props.rowsData;
    return (
      <div>
        {/* web view */}
        <div className="fe-audits-table-content">
          <SelectTable
            style={{
              width: "100%",
              borderTop: "1px solid rgb(221, 221, 221)",
              borderBottom: "0px",
              borderRight: "0px",
              borderLeft: "0px"
            }}
            ref={r => (this.checkboxTable = r)}
            toggleSelection={this.toggleSelection}
            selectAll={this.state.selectAll}
            toggleAll={this.toggleAll}
            selectType="checkbox"
            isSelected={this.isSelected}
            loading={this.props.isLoading && this.props.rowsData.length <= 0}
            defaultPageSize={10}
            minRows={3}
            data={this.props.rowsData}
            PaginationComponent={Pagination}
            columns={this.renderColumns()}
          />
        </div>
        {/* mobile view */}
        <div className="fe-audits-table-content-mobile">
          {data &&
            data.map((audit: any) => {
              return (
                <div className="fe-audits-table-content-div" key={audit._id}>
                  <div className="fe-audits-info-div">
                    <div
                      className={`fe-audits-mark-div fe-audits-${audit.severity.toLowerCase()}`}
                    />
                    <div className="fe-audits-section-one">
                      <div className="fe-audits-address-div">
                        <span className="fe-audits-info-name">{audit.ip}</span>
                        <br />
                        {/* <img src={flagIcon} alt="flag" width={7} height={7} /> */}
                        {/* <span className="fe-audits-info-flag-name"> Isreal</span> */}
                      </div>
                      <div className="fe-audits-time-div">
                        <span className="fe-audits-info-name">
                          {moment(audit.time).fromNow()}
                        </span>
                        <br />
                        <span className="fe-audits-info-name">
                          {moment(audit.time).format("hh:mm:ss")}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div className="fe-audits-detail-content-div">
                    <div className="fe-audits-user-div">
                      {/* <div className="fe-audits-image-div">
                  <img src={profileIcon} alt="profile" />
                </div> */}
                      <div className="fe-audits-detail-div">
                        {/* <span className="fe-audits-name">Francisco Pattons</span> */}
                        {/* <br /> */}
                        <span className="fe-audits-email">{audit.user}</span>
                      </div>
                    </div>
                    <div>
                      <span className="fe-audits-status-span">
                        {audit.message}
                      </span>
                    </div>
                    <div className="fe-audits-detail-tags">
                      <div className="fe-audits-detail-content">
                        <div className="fe-audits-detail-content-sections">
                          <span className="fe-audits-head-span">Resource</span>
                          <span className="fe-audits-child-span">
                            {audit.resource}
                          </span>
                        </div>
                        <div className="fe-audits-detail-content-sections">
                          <span className="fe-audits-head-span">Action</span>
                          <span className="fe-audits-child-span">
                            {audit.action.length > 10
                              ? audit.action.substr(0, 10) + "..."
                              : audit.action}
                          </span>
                        </div>
                      </div>
                      {/* <div className="fe-audits-menu">
                        <i className="fe-audits-fa fa-ellipsis-v" />
                      </div> */}
                    </div>
                  </div>
                </div>
              );
            })}
        </div>
      </div>
    );
  }
}
