import React, { Component, memo } from "react";
import { Container, Row, Col } from "react-bootstrap";
import { makeStyles, 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 AccountCircle from '@material-ui/icons/AccountCircle';
var ct = require("../../library/CustomTable");
const getMuiTheme = () => createMuiTheme(ct.customTable());
const options = ct.customOptions();

class UserRole extends Component {
  constructor(props) {
    super(props)
    this.state = {
      listRole: [],
      indexData: {},
      add: false,
      edit: false,
      search: ''
    }
  }

  componentDidMount() {
    this.getRole()
  }

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

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

  getRole() {
    api.create().getRole().then((response) => {
      // console.log(response)
      if (response.data.status == 'success') {
        let data = response.data.data
        let listData = data.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 {
        alert(response.data.message)
      }
      // console.log(response.data.data)
    })
  }

  searchRole() {
    let payload = {
      "keyword": this.state.search
    }
    api.create().searchRole(payload).then((response) => {
      if (response.data.status == 'success') {
        let data = response.data.data
        let listData = data.map((item,index) => {
          return [index, item.role_id, item.role_name, item.access, item.status]
        })
        this.setState({listRole: listData})
      } else {
        alert(response.data.message)
      }
    })  
  }

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

  render() {
    const columns = [{
      name: "Action",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <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[4] === "Aktif" ?
                    <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] === "Aktif" ? "#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] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{titleCase(val)}</span>
            </div >
          );
        }
      }
    }, {
      name: "Hak Akses",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              <span style={{ color: tableMeta.rowData[4] === "Aktif" ? "#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] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
            </div >
          );
        }
      }
    }]
    const data = [
      ["1", "1", "Laporan Bulanan - September 2020", "1 (20 Oktober 2020)", "Belum Disetujui"],
      ["2", "2", "Laporan Bulanan - September 2020", "1 (20 Oktober 2020)", "Belum Disetujui"],
      ["3", "3", "Budget Tahunan 2021", "0 (20 Oktober 2020)", "Belum Disetujui"],
      ["4", "4", "Laporan Bulanan - September 2020", "0 (20 Oktober 2020)", "Belum Disetujui"],
      ["5", "5", "Budget Tahunan 2021", "0 (20 Oktober 2020)", "Belum Disetujui"],
    ]
    return (
      <div style={{ height: this.props.height }}>
        {/* <Row> */}
        <div style={{ height: 199, backgroundColor: '#354960', width: '100%' }} />
        <div>
          <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingRight: 25, paddingLeft: 25, marginTop: -150 }}>
            <label style={{ fontFamily: 'nunito', color: 'white', width: '20%', alignSelf: 'center', fontSize: 18}}>Master Data - Role & Otorisasi</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.searchRole()
                      } else {
                        this.getRole()
                      }
                    });
                  }}
                  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>
            {/* <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' }}>
              <img src={Images.add} onClick={() => this.setState({add: true})}/>
            </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);