import React, { Component } from "react";
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';
import SearchIcon from '@material-ui/icons/Search';
import Images from "../../assets/Images";
import MUIDataTable, {TableBodyCell} from "mui-datatables";
import AddUser from './User/AddUser';
import EditUser from './User/EditUser'
import api from "../../api";
import { titleCase } from "../../library/Utils";
import { InputAdornment, Snackbar, InputBase } from "@material-ui/core";
import MuiAlert from '@material-ui/lab/Alert';
import UploadFile from "../../library/Upload";
import { withStyles } from '@material-ui/core/styles';
import { ExcelRenderer } from 'react-excel-renderer';
import ReactTooltip from "react-tooltip";
import PopUpFailedSave from "../../library/PopUpFailedSave";
import Constant from "../../library/Constant";
import { css } from "@emotion/core";
import PropagateLoader from "react-spinners/PropagateLoader"
import Tooltip from '@material-ui/core/Tooltip';

const LightTooltip = withStyles((theme) => ({
  tooltip: {
    backgroundColor: theme.palette.common.white,
    color: 'rgba(0, 0, 0, 0.87)',
    boxShadow: theme.shadows[1],
    fontSize: 11,
  },
}))(Tooltip);

const override = css`
  display: block;
  margin: 0 auto;
  border-color: red;
`;

var ct = require("../../library/CustomTable");
const getMuiTheme = () => createMuiTheme(ct.customTable());
const options = ct.customOptions();

const Alert = withStyles({
})((props) => <MuiAlert elevation={6} variant="filled" {...props} />);



export default class UserRole extends Component {
  constructor(props) {
    super(props)
    this.state = {
      listUser: [],
      indexData: {},
      add: false,
      edit: false,
      popupDel: false,
      visibleUser: true,
      buttonError: false,
      alert: false,
      tipeAlert: '',
      messageAlert: '',
      buttonCreate: false,
      buttonEdit: false,
      buttonDelete: false,
      load: false,
      judul: '',
      loading: false
    }
  }

  componentDidMount() {
    this.daskdkas()
    this.getUser()
    this.getPermission()
  }

  async daskdkas() {
    let res = await localStorage.getItem(Constant.TOKEN)
    // console.log(res)
  }

  closeEdit() {
    this.setState({ edit: false })
  }

  closeAdd() {
    this.setState({ add: false })
  }

  getUser() {
    this.setState({loading: true})
    api.create().getUser().then((response) => {
      if (response.data) {
        if (response.ok) {
          if (response.data.status === 'success') {
            // console.log(response.data);
            let data = response.data.data
            let listData = data.sort((a, b) => a.user_id - b.user_id).map((item, index) => {
              return [index, item.user_id, item.fullname === null ? '-' : item.fullname, item.email, item.role_name, item.totalCompany, item.status]
            })
            this.setState({ listUser: listData }, () => {
              setTimeout(() => {
                this.setState({loading: false})
              }, 2000);
            })
          } else {
            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
              if (response.data.message.includes("Someone Logged In")) {
                setTimeout(() => {
                  localStorage.removeItem(Constant.TOKEN)
                  window.location.reload();
                }, 1000);
              }
            })
          }
        } else {
          this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' }, () => {
            this.setState({loading: false})
          })
        }
      } else {
        this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' }, () => {
          this.setState({loading: false})
        })
      }
    })
  }

  getPermission() {
    let payload = {
      menu: "user"
    }
    api.create().getPermission(payload).then(response => {
      // console.log(response)
      if (response.data) {
        if (response.data.status === "success") {
          this.setState({
            buttonCreate: response.data.data.create,
            buttonEdit: response.data.data.edit,
            buttonDelete: response.data.data.delete,
            load: true
          })
        } else {
          this.setState({ load: true })
        }
      }
    })
  }

  searchUser() {
    this.setState({loading: true})
    let payload = {
      "keyword": this.state.search
    }
    api.create().searchUser(payload).then((response) => {
      if (response.data) {
        if (response.ok) {
          if (response.data.status === 'success') {
            let data = response.data.data
            let listData = data.sort((a, b) => a.user_id - b.user_id).map((item, index) => {
              return [index, item.user_id, item.fullname == null ? '-' : item.fullname, item.email, item.role_name, item.totalCompany, item.status]
            })
            this.setState({ listUser: listData }, () => {
              setTimeout(() => {
                this.setState({loading: false})
              }, 1500);
            })
          } else {
            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
              if (response.data.message.includes("Someone Logged In")) {
                setTimeout(() => {
                  localStorage.removeItem(Constant.TOKEN)
                  window.location.reload();
                }, 1000);
              }
            })
          }
        } else {
          this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' }, () => {
            this.setState({loading: false})
          })
        }
      } else {
        this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' }, () => {
          this.setState({loading: false})
        })
      }
    })
  }

  fileHandler = (event) => {
    let fileObj = event
    ExcelRenderer(fileObj, (err, resp) => {
      if (err) {
        // console.log(err);
      }
      else {
        // let judul = resp.rows[0]
        let isi = resp.rows.slice(3)
        let payload = []
        // console.log(isi)
        isi.map((item, index) => {
          if (item.length > 0) {
            payload.push({
              id: index + 1,
              fullname: item[0] == undefined? '' : item[0],
              email: item[1] == undefined? '' : item[1],
              role: item[2] == undefined? '' : item[2],
              start_date: item[3] == undefined? '' : item[3],
              end_date: item[4] == undefined? '' : item[4],
            })
          }
        })
        let body = {
          user: payload
        }
        // console.log(resp.rows[1])
        this.setState({ payload: body, rows: [], judul: resp.rows[1][0] })
      }
    });
  }

  deleteUser() {
    let data = this.state.rowData
    api.create().deleteUser(data[1]).then((response) => {
      this.setState({popupDel: false})
      if (response.data) {
            if (response.ok) {
                if (response.data.status == 'success') {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'success' })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        if (response.data.message.includes("Someone Logged In")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
            }
        } else {
            this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
        }
        this.getUser()
    })
  }

  checkUpload(){
    api.create().checkUploadUser(this.state.payload).then(response => {
      // console.log(response);
      if (response.data) {
        if (response.ok) {
          if (response.data.status === "success") {
            let dataRow = response.data.data.map((item, index) => {
              return [
                index + 1,
                item.fullname,
                item.email,
                item.role,
                item.start_date,
                item.end_date,
                item.error
              ]
            })

            let columns = [
              "Data",
              {
                name: "Full Name",
                options: {
                  customBodyRender: (val, tableMeta) => {
                    let check = null
                    if (tableMeta.rowData[6] != null) {
                      check = tableMeta.rowData[6].findIndex((val) => val.field.includes('fullname'))
                      if (check > -1) {
                        this.setState({ buttonError: true })
                        // console.log('masuk')
                      }
                    }
                    return (
                      <div style={{ display: 'flex' }}>
                        {tableMeta.rowData[6] != null && check > -1 ?
                          <LightTooltip title={tableMeta.rowData[6][check].message} arrow>
                            <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val == ''? 'Empty' : val}</span>
                          </LightTooltip>
                          :
                          <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val == ''? 'Empty' : val}</span>
                        }
                      </div >
                    );
                  }
                }},
              {
                name: "Email",
                options: {
                  customBodyRender: (val, tableMeta) => {
                    // console.log(tableMeta)
                    let check = null
                    if (tableMeta.rowData[6] != null) {
                      check = tableMeta.rowData[6].findIndex((val) => val.field.includes('email'))
                      if (check > -1) {
                        this.setState({ buttonError: true })
                      }
                    }
                    return (
                      <div style={{ display: 'flex' }}>
                        {tableMeta.rowData[6] != null && check > -1 ?
                          <LightTooltip title={tableMeta.rowData[6][check].message} arrow>
                            <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val == ''? 'Empty' : val}</span>
                          </LightTooltip>
                          :
                          <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val == ''? 'Empty' : val}</span>
                        }
                      </div >
                    );
                  }
                }
              },
              {
                name: "Role",
                options: {
                  customBodyRender: (val, tableMeta) => {
                    let check = null
                    if (tableMeta.rowData[6] != null) {
                      check = tableMeta.rowData[6].findIndex((val) => val.field.includes('role'))
                      if (check > -1) {
                        this.setState({ buttonError: true })
                        // console.log(tableMeta.rowData[6])
                      }
                    }
                    return (
                      <div style={{ display: 'flex' }}>
                        {tableMeta.rowData[6] != null && check > -1 ?
                          <LightTooltip title={tableMeta.rowData[6][check].message} arrow>
                            <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val == ''? 'Empty' : val}</span>
                          </LightTooltip>
                          :
                          <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val == ''? 'Empty' : val}</span>
                        }
                      </div >
                    );
                  }
                }
              },
              {
                name: "Valid From",
                options: {
                  customBodyRender: (val, tableMeta) => {
                    let check = null
                    if (tableMeta.rowData[6] != null) {
                      check = tableMeta.rowData[6].findIndex((val) => val.field.includes('start_date'))
                      if (check > -1) {
                        this.setState({ buttonError: true })
                        // console.log('masuk')
                      }
                    }
                    return (
                      <div style={{ display: 'flex' }}>
                        {tableMeta.rowData[6] != null && check > -1 ?
                          <LightTooltip title={tableMeta.rowData[6][check].message} arrow>
                            <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val == ''? 'Empty' : val}</span>
                          </LightTooltip>
                          :
                          <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val == ''? 'Empty' : val}</span>
                        }
                      </div >
                    );
                  }
                }
              },
              {
                name: "Valid To",
                options: {
                  customBodyRender: (val, tableMeta) => {
                    let check = null
                    if (tableMeta.rowData[6] != null) {
                      check = tableMeta.rowData[6].findIndex((val) => val.field.includes('end_date'))
                      if (check > -1) {
                        this.setState({ buttonError: true })
                        // console.log('masuk')
                      }
                    }
                    return (
                      <div style={{ display: 'flex' }}>
                        {tableMeta.rowData[6] != null && check > -1 ?
                          <LightTooltip title={tableMeta.rowData[6][check].message} arrow>
                            <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val == ''? 'Empty' : val}</span>
                          </LightTooltip>
                          :
                          <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val == ''? 'Empty' : val}</span>
                        }
                      </div >
                    );
                  }
                }
              },
              {
                name: "",
                options: {
                  display: false
                }
              }
            ]

            this.setState({
              dataLoaded: true,
              cols: columns,
              rows: dataRow,  
              visibleUpload: false, 
              visibleUser: false
            }, () => console.log(dataRow));
          } else {
            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
              if (response.data.message.includes("Someone Logged In")) {
                setTimeout(() => {
                  localStorage.removeItem(Constant.TOKEN)
                  window.location.reload();
                }, 1000);
              }
            })
          }
        } else {
          this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
        }
      } else {
        this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
      }
    })
  }

  downloadFile = async () => {
    let res = await fetch(
      `${process.env.REACT_APP_URL_MAIN_BE}/public/attachment/download_file?fileName=UserTemplate&&fileType=xlsx`
    )
    res = await res.blob()
    // console.log(res)
    if (res.size > 0) {
      let url = window.URL.createObjectURL(res);
      let a = document.createElement('a');
      a.href = url;
      a.download = 'User Template.xlsx';
      a.click();
    }
  }

  downloadDataTables = async () => {
    let res = await fetch(`${process.env.REACT_APP_URL_MAIN_BE}/public/user/export_user`)
    res = await res.blob()
    // console.log(res)
    if (res.size > 0) {
      let url = window.URL.createObjectURL(res);
      let a = document.createElement('a');
      a.href = url;
      a.download = 'User.xlsx';
      a.click();
    }
  }

  updateUser(payload) {
    api.create().updateUser(payload).then((response) => {
      // console.log(response.data.message)
      // console.log(response.data.status)
      if (response.data) {
        if (response.ok) {
          if (response.data.status === 'success') {
            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'success' })
            this.getUser()
            this.closeEdit()
            window.location.reload();
          } else {
            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
              if (response.data.message.includes("Someone Logged In")) {
                setTimeout(() => {
                  localStorage.removeItem(Constant.TOKEN)
                  window.location.reload();
                }, 1000);
              }
            })
          }
        } else {
          this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
        }
      } else {
        this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
      }
    })
  }

  createUser(payload) {
    // console.log('Mode Create')
    api.create().createUser(payload).then((response) => {
      // console.log(response.data)
      // if (String(response.data.status).toLocaleUpperCase === 'Success' || String(response.data.status).toLocaleUpperCase === 'success') {
      if (response.data) {
        if (response.ok) {
          if (response.data.status === 'success') {
            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'success', add: false })
            this.getUser()
            window.location.reload();
          } else {
            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
              if (response.data.message.includes("Someone Logged In")) {
                setTimeout(() => {
                  localStorage.removeItem(Constant.TOKEN)
                  window.location.reload();
                }, 1000);
              }
            })
          }
        } else {
          this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
        }
      } else {
        this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
      }

      // } else {
      // alert(response.data.message)
      //     this.props.onClickClose()
      //     this.props.refresh()
      // }
    })
  }

  _handleKeyDown(e) {
    if (e.key === 'Enter') {
      if (this.state.search.length > 0) {
        this.searchUser()
      } else {
        this.getUser()
      }
    }
  }

  uploadUser() {
    // console.log(JSON.stringify(this.state.payload))
    api.create().uploadUser(this.state.payload).then(response => {
      this.setState({buttonError: false})
      // console.log(JSON.stringify(response))
      if (response.data) {
        if (response.ok) {
          if (response.data.status === "success") {
            this.getUser()
            this.setState({ visibleUser: true, alert: true, messageAlert: response.data.message, tipeAlert: 'success', payload: [], rows: [], judul: '' })
          } else {
            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
              if (response.data.message.includes("Someone Logged In")) {
                setTimeout(() => {
                  localStorage.removeItem(Constant.TOKEN)
                  window.location.reload();
                }, 1000);
              }
            })
          }
        } else {
          this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
        }
      } else {
        this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
      }
    })
  }

  closeAlert() {
    this.setState({ alert: false })
  }

  render() {
    const columns = [{
      name: "Action",
      options: {
        filter: false,
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              {/* {tableMeta.rowData[6] === "Active" ? */}
              {this.state.buttonEdit && (
                <span>
                  <a data-tip={'Edit'} data-for="edit">
                    <button
                      style={{
                        backgroundColor: 'transparent',
                        cursor: 'pointer',
                        borderColor: 'transparent',
                      }}
                      // onClick={() => console.log(tableMeta.rowData[1])}
                      onClick={() => this.setState({ edit: true, indexData: tableMeta.rowData[1] })}
                    >
                      <img src={Images.editCopy} />
                    </button>
                  </a>
                  <ReactTooltip border={true} id="edit" place="bottom" type="light" effect="solid" />
                </span>
              )}
              {this.state.buttonDelete && (
                <span>
                  <a data-tip={'Delete'} data-for="delete">
                    <button
                        style={{
                            backgroundColor: 'transparent',
                            cursor: 'pointer',
                            borderColor: 'transparent',
                            marginLeft: 10
                        }}
                        onClick={() => this.setState({popupDel: true, rowData: tableMeta.rowData})}
                    >
                        <img src={Images.delete} />
                    </button>
                  </a>
                  <ReactTooltip border={true} id="delete" place="bottom" type="light" effect="solid" />
                </span>
              )}
              {/* :
                null
              } */}
            </div >
          );
        }
      }
    }, {
      name: "ID",
      options: {
        // filter: false,
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[6] === "Active" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{titleCase(val)}</span>
            </div >
          );
        }
      }
    }, {
      name: "Full Name",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[6] === "Active" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{titleCase(val)}</span>
            </div >
          );
        }
      }
    }, {
      name: "Email",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[6] === "Active" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
            </div >
          );
        }
      }
    }, {
      name: "Role",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[6] === "Active" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{titleCase(val)}</span>
            </div >
          );
        }
      }
    }, {
      name: "Company",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[6] === "Active" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{titleCase(val)}</span>
            </div >
          );
        }
      }
    }, {
      name: "Status",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[6] === "Active" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{titleCase(val)}</span>
            </div >
          );
        }
      }
    }]
    const loadingComponent = (
      <div style={{position: 'absolute', zIndex: 110, top: 0, left: 0, width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'rgba(255,255,255,0.8)'}}>
        <PropagateLoader
          // css={override}
          size={20}
          color={"#274B80"}
          loading={this.state.loading}
        />
      </div>
    );
    return (
      <div style={{ height: this.props.height }}>
        {/* <Row> */}
        <div className={"main-color"} style={{ height: 195, width: '100%' }} />
        <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
          <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
            {this.state.messageAlert}
          </Alert>
        </Snackbar>
        {this.state.visibleUser ? <div>
          {this.state.load && (
            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingRight: 25, paddingLeft: 25, marginTop: -180 }}>
              <label style={{ color: 'white', fontSize: 16, alignSelf: 'center', width: '20%', }}>Master Data - User</label>
              {/* <div style={{ width: '60%', justifyContent: 'center', display: 'flex', borderWidth: 2, alignItems: 'center' }}>
                <div style={{ width: '50%', backgroundColor: 'white', padding: 10, borderRadius: 7.5 }}>
                  <TextField
                    id="input-with-icon-textfield"
                    name="search"
                    value={this.state.search}
                    placeholder={'Search'}
                    onChange={(e) => {
                      this.setState({ search: e.target.value }, () => {
                        if (this.state.search.length > 0) {
                          this.searchUser()
                        } else {
                          this.getUser()
                        }
                      });
                    }}
                    onKeyDown={(e) => this._handleKeyDown(e)}
                    style={{ width: '100%', borderBottomWidth: 0, borderBottomColor: 'red' }}
                    InputProps={{
                      style: { fontFamily: 'nunito', borderBottomColor: 'white' },
                      startAdornment: (
                        <InputAdornment position="start">
                          <SearchIcon />
                        </InputAdornment>
                      ),
                    }}
                  />
                </div>
              </div> */}
              {/* <div style={{ color: 'white', width: '50%', height: 37, display: 'flex', backgroundColor: 'white', borderWidth: 2, alignItems: 'center', borderRadius: 6, paddingLeft: 5, paddingRight: 5, alignSelf: 'center' }}>
                <img src={Images.searchBlack} style={{ marginRight: 10 }} />
                <InputBase
                  style={{ width: '100%' }}
                  placeholder="Search"
                  value={this.state.search}
                  onChange={(e) => {
                    this.setState({ search: e.target.value }, () => {
                      if (this.state.search.length > 0) {
                        this.searchUser()
                      } else {
                        this.getUser()
                      }
                    });
                  }}
                  inputProps={{ 'aria-label': 'naked' }}
                />
              </div> */}
              {/* <label style={{ color: 'white', width: '60%', justifyContent: 'center', display: 'flex', backgroundColor: 'white', borderWidth: 2, alignItems: 'center' }}>Search</label> */}
              <div style={{ width: '20%', justifyContent: 'flex-end', display: 'flex' }}>
                <a data-tip={'Download Template'} data-for="template">
                  <button
                    style={{
                      backgroundColor: 'transparent',
                      cursor: 'pointer',
                      borderColor: 'transparent',
                      margin: 5
                    }}
                    onClick={() => this.downloadFile()}
                  >
                    <img src={Images.template} />
                  </button>
                </a>
                <ReactTooltip border={true} id="template" place="bottom" type="light" effect="solid" />
                {this.state.buttonCreate && (
                  <a data-tip={'Upload'} data-for="upload">
                    <button
                      style={{
                        backgroundColor: 'transparent',
                        cursor: 'pointer',
                        borderColor: 'transparent',
                        margin: 5
                      }}
                      onClick={() => this.setState({ visibleUpload: true })}
                    >
                      <img src={Images.upload} />
                    </button>
                  </a>
                )}
                <ReactTooltip border={true} id="upload" place="bottom" type="light" effect="solid" />
                <a data-tip={'Download'} data-for="download">
                  <button
                    style={{
                      backgroundColor: 'transparent',
                      cursor: 'pointer',
                      borderColor: 'transparent',
                      margin: 5
                    }}
                    onClick={() => this.downloadDataTables()}
                  >
                    <img src={Images.download} />
                  </button>
                </a>
                <ReactTooltip border={true} id="download" place="bottom" type="light" effect="solid" />
                {this.state.buttonCreate && (
                  <a data-tip={'Add New'} data-for="add">
                    <button
                      style={{
                        backgroundColor: 'transparent',
                        cursor: 'pointer',
                        borderColor: 'transparent',
                        margin: 5,
                        marginRight: 20
                      }}
                      onClick={() => this.setState({ add: true })}
                    >
                      <img src={Images.add} />
                    </button>
                  </a>
                )}
                <ReactTooltip border={true} id="add" place="bottom" type="light" effect="solid" />
              </div>
            </div>
          )}
          <div style={{ padding: 25}}>
            {this.state.loading && loadingComponent}
            <MuiThemeProvider theme={getMuiTheme()}>
              <MUIDataTable
                data={this.state.listUser}
                columns={columns}
                options={options}
              />
            </MuiThemeProvider>
          </div>
        </div> :
          <div>
            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingRight: 25, paddingLeft: 25, marginTop: -150 }}>
              <label style={{ color: 'white', fontSize: 16, alignSelf: 'center' }}>Preview Data</label>
            </div>
            <div style={{ padding: 25 }}>
              {this.state.dataLoaded && (
                <MuiThemeProvider theme={getMuiTheme()}>
                  <MUIDataTable
                    theme={getMuiTheme()}
                    data={this.state.rows}
                    columns={this.state.cols}
                    options={options}
                  />
                </MuiThemeProvider>
              )}
            </div>
            <div style={{ display: 'flex', width: '100%', placeContent: 'flex-end', padding: 20 }}>
              <button
                type="button"
                onClick={() => this.setState({ visibleUser: true, payload: [], rows: [], judul: '', buttonError: false })}
                style={{ marginRight: 20 }}
              >
                <div style={{ width: 102, height: 30, border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                  <span style={{ color: '#354960', fontSize: 11 }}>Cancel</span>
                </div>
              </button>
              <button
                type="button"
                disabled={this.state.buttonError === true ? true : false}
                onClick={() => this.uploadUser()}
                style={{}}
              >
                <div style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                  <span style={{ color: '#fff', fontSize: 11 }}>Save</span>
                </div>
              </button>
            </div>
          </div>
        }
        {this.state.add && (
          <AddUser
            onClickClose={this.closeAdd.bind(this)}
            refresh={this.getUser.bind(this)}
            data={this.state.indexData}
            createUser={this.createUser.bind(this)}
          />
        )}
        {this.state.edit && (
          <EditUser
            onClickClose={this.closeEdit.bind(this)}
            refresh={this.getUser.bind(this)}
            updateUser={this.updateUser.bind(this)}
            data={this.state.indexData}
          />
        )}
        {this.state.popupDel && (
          <div className="test app-popup-show">
              <div className="popup-content background-white border-radius" style={{ borderRadius: 8 }}>
                  <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 20 }}>
                      <img src={Images.failed} />
                  </div>
                  <div style={{ display: 'grid', justifyContent: 'center', marginTop: 20, paddingBottom: 20 }}>
                      <span style={{ textAlign: 'center', fontSize: 14, fontWeight: 'bold', fontFamily: 'Nunito Sans, sans-serif' }}>
                        Delete {titleCase(this.state.rowData[2])} ?
                      </span>
                  </div>
                  <div className="border-top grid grid-2x" style={{ height: 56, backgroundColor: '#f5f5f5', paddingLeft: 20, paddingRight: 20 }}>
                      <div className="column-1" style={{ alignSelf: 'center' }}>
                          <button
                              type="button"
                              onClick={()=> this.setState({popupDel: false})}
                          >
                              <div style={{ width: 102, height: 30, border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                  <span style={{ color: '#354960', fontSize: 11 }}>Cancel</span>
                              </div>
                          </button>
                      </div>
                      <div className="column-2" style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
                          <button
                              type="button"
                              onClick={()=> this.deleteUser()}
                          >
                              <div style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                  <span style={{ color: '#fff', fontSize: 11 }}>Delete</span>
                              </div>
                          </button>
                      </div>
                  </div>
              </div>
          </div>
          // <div className="test app-popup-show">
          //   <div className="popup-content background-white border-radius" style={{ borderRadius: 8, padding: 50 }}>
          //     <div style={{ display: 'flex', justifyContent: 'center' }}>
          //         <img src={Images.failed} />
          //     </div>
          //     <div style={{ display: 'grid', justifyContent: 'center', marginTop: 20 }}>
          //       <span style={{ textAlign: 'center', fontSize: 14, fontWeight: 'bold' }}>
          //           Delete {titleCase(this.state.rowData[2])} ?
          //       </span>
          //       {/* <span style={{ textAlign: 'center', fontSize: 14, fontWeight: 'bold' }}>
          //           {`Please try again later.`}
          //       </span> */}
          //     </div>
          //     <div style={{ display: 'flex', justifyContent: 'center', marginTop: 24 }}>
          //       <button
          //           className={"btn-save"}
          //           onClick={()=> this.setState({popupDel: false})}
          //       >
          //           <span style={{ color: 'white' }}>Cancel</span>
          //       </button>
          //       <button
          //           className={"btn-save"}
          //           style={{ marginLeft: 50}}
          //           onClick={()=> this.deleteUser()}
          //       >
          //           <span style={{ color: 'white' }}>Delete</span>
          //       </button>
          //     </div>
          //   </div>
          // </div>
        )}
        {this.state.popupError && (
          <PopUpFailedSave onClickClose={() => this.setState({ popupError: false })} />
        )}
        {this.state.visibleUpload && (
          <div className="test app-popup-show">
            <div className="popup-content background-white border-radius" style={{ borderRadius: 8 }}>
              <div className="popup-panel grid grid-2x main-color" style={{ height: 64, borderTopRightRadius: 8, borderTopLeftRadius: 8 }}>
                <div className="col-1" style={{ maxWidth: "inherit", display: 'flex', alignItems: 'center' }}>
                  <div className="popup-title">
                    <span style={{ color: '#fff', fontSize: 16, fontWeight: 'bold' }}>Upload File</span>
                  </div>
                </div>
                <div className="col-2 content-right" style={{ maxWidth: "inherit", alignSelf: 'center' }}>
                  <button
                    type="button"
                    className="btn btn-circle btn-white"
                    onClick={() => this.setState({ visibleUpload: false })}
                  >
                    <img src={Images.close} />
                  </button>
                </div>
              </div>
              <UploadFile
                type={this.state.uploadStatus}
                percentage={this.state.percentage}
                result={this.state.result}
                acceptedFiles={["xlsx"]}
                onHandle={(dt) => {
                  this.fileHandler(dt)
                  this.setState({ uploadStatus: 'idle', percentage: '0' })
                }}
                onUpload={() => {
                  String(this.state.judul).includes("MASTER") && String(this.state.judul).includes("DATA") && String(this.state.judul).includes("USER") ?
                    this.checkUpload() :
                    this.setState({ alert: true, messageAlert: "Invalid Template", tipeAlert: 'warning' })
                }}
              />
            </div>
          </div>
        )}
      </div>
    );
  }
}
