import React, { Component, memo } from "react";
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';
import SearchIcon from '@material-ui/icons/Search';
import Images from "../../../assets/Images";
import MUIDataTable from "mui-datatables";
import AddRole from './AddRole';
import EditRole from './EditRole'
import api from "../../../api";
import { titleCase } from "../../../library/Utils";
import InputAdornment from '@material-ui/core/InputAdornment';
import TextField from '@material-ui/core/TextField';
import { InputBase, Snackbar } from "@material-ui/core";
import ReactTooltip from "react-tooltip";
import MuiAlert from '@material-ui/lab/Alert';
import { withStyles } from '@material-ui/core/styles';
import Constant from "../../../library/Constant";
import PropagateLoader from "react-spinners/PropagateLoader"

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

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

class UserRole extends Component {
  constructor(props) {
    super(props)
    this.state = {
      listRole: [],
      indexData: {},
      add: false,
      edit: false,
      search: '',
      alert: false,
      tipeAlert: '',
      messageAlert: '',
      buttonCreate: false,
      buttonEdit: false,
      buttonDelete: false,
      load: false,
      loading: false
    }
  }

  componentDidMount() {
    
    this.getRole()
    this.getPermission()
  }

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

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

  getRole() {
    this.setState({loading: true})
    api.create().getRole().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.role_id - b.role_id).map((item, index) => {
                  return [index, item.role_id, item.role_name, item.access, item.status]
                })
                // console.log(listData)
                this.setState({ listRole: listData }, () => {
                  setTimeout(() => {
                    this.setState({loading: false})
                  }, 2000);
                })
                // this.setState({listRole: response.data.data}, () => {
                //   console.log(this.state.listRole)
                // })
        
              } else {
                this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false}, () => {
                    if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                        setTimeout(() => {
                            localStorage.removeItem(Constant.TOKEN)
                            window.location.reload();
                        }, 1000);
                    }
                })
              }
        } else {
            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error', loading: false })
        }
      } else {
            this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
      }
    })
  }

  getPermission() {
    let payload = {
        menu: "user role"
    }
    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 })
            }
        }
    })
}

  searchRole() {
    let payload = {
      "keyword": this.state.search
    }
    api.create().searchRole(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.role_id - b.role_id).map((item, index) => {
                  return [index, item.role_id, item.role_name, item.access, item.status]
                })
                this.setState({ listRole: listData })
              } else {
                this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                    if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                        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' })
      }
    })
  }

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

  handleChange(e) {
    let data = this.state
    window.requestIdleCallback((e) => this.setState({ ...data, [e.target.name]: e.target.value }, () => {
      // alert('asdk')

    }))
  }

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

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

  render() {
    const columns = [{
      name: "Action",
      options: {
        filter: false,
        customBodyRender: (val, tableMeta) => {
          // console.log(tableMeta);
          return (
            <div style={{ display: 'flex' }}>
              {this.state.buttonEdit && (
                <button
                  style={{
                    backgroundColor: 'transparent',
                    cursor: 'pointer',
                    borderColor: 'transparent',
                  }}
                  // onClick={() => console.log(tableMeta.rowData[1])}
                  onClick={() => this.setState({ edit: true, indexData: tableMeta.rowData[1] })}
                >
                  <div style={{ display: 'flex' }}>
                    {tableMeta.rowData[2] !== "superadmin" ?
                      <img src={Images.editCopy} /> :
                      null
                    }
                  </div >
                </button>
              )}
              {this.state.buttonDelete && (
                <button
                  style={{
                      backgroundColor: 'transparent',
                      cursor: 'pointer',
                      borderColor: 'transparent',
                      marginLeft: 10
                  }}
                  onClick={() => this.setState({popupDel: true, rowData: tableMeta.rowData})}
              >
                {tableMeta.rowData[2] !== "superadmin" ?
                  <img src={Images.delete} /> :
                  null
                }
              </button>
              )}
            </div >
          );
        }
      }
    }, {
      name: "ID",
      options: {
        // filter: false,
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[4] === "Active" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
            </div >
          );
        }
      }
    }, {
      name: "User Role",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[4] === "Active" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{titleCase(val)}</span>
            </div >
          );
        }
      }
    }, {
      name: "Access Rights",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[4] === "Active" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val + ' Modul'}</span>
            </div >
          );
        }
      }
    }, {
      name: "Status",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[4] === "Active" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{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>
        <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 - Role & Authorization</label>
              {/* <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.searchRole()
                      } else {
                        this.getRole()
                      }
                    });
                  }}
                  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' }}>
                {this.state.buttonCreate && (
                  <a data-tip={'Add New'} data-for="create">
                    <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="create" place="bottom" type="light" effect="solid" />
              </div>
            </div>
          )}
          <div style={{ padding: 25 }}>
          {this.state.loading && loadingComponent}
            <MuiThemeProvider theme={getMuiTheme()}>
              <MUIDataTable
                data={this.state.listRole}
                columns={columns}
                options={options}
              />
            </MuiThemeProvider>
          </div>
        </div>
        {this.state.add && (
          <AddRole
            onClickClose={this.closeAdd.bind(this)}
            refresh={this.getRole.bind(this)}
            data={this.state.indexData}
          />
        )}
        {this.state.edit && (
          <EditRole
            onClickClose={this.closeEdit.bind(this)}
            refresh={this.getRole.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.deleteRole()}
                          >
                              <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.deleteRole()}
          //       >
          //           <span style={{ color: 'white' }}>Delete</span>
          //       </button>
          //     </div>
          //   </div>
          // </div>
        )}
      </div>
    );
  }
}

export default memo(UserRole);