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 './UserRole/AddRole';
import EditRole from './UserRole/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';

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,
      load: false
    }
  }

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

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

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

  getRole() {
    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 })
                // this.setState({listRole: response.data.data}, () => {
                //   console.log(this.state.listRole)
                // })
        
              } else {
                this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }) 
              }
        } else {
            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
        }
      } else {
            this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
      }
    })
  }

  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,
                    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' }) 
              }
        } 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 })
  }

  render() {
    const columns = [{
      name: "Action",
      options: {
        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>
              )}
            </div >
          );
        }
      }
    }, {
      name: "ID",
      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 >
          );
        }
      }
    }, {
      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 >
          );
        }
      }
    }]
    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>
          <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingRight: 25, paddingLeft: 25, marginTop: -118 }}>
            <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={'Create'} data-for="create">
                  <button
                    style={{
                      backgroundColor: 'transparent',
                      cursor: 'pointer',
                      borderColor: 'transparent',
                      margin: 5
                    }}
                    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 }}>
            <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}
          />
        )}
      </div>
    );
  }
}

export default memo(UserRole);