import React, { Component } 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 AddUser from './User/AddUser';
import EditUser from './User/EditUser'
import api from "../../api";
import { titleCase } from "../../library/Utils";
import { InputAdornment, TextField } from "@material-ui/core";
import UploadFile from "../../library/Upload";
import { ExcelRenderer } from 'react-excel-renderer';
import ReactTooltip from "react-tooltip";
import PopUpFailedSave from "../../library/PopUpFailedSave";

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

const tesss = [{
  name: "Data Ke-",
  options: {
    customBodyRender: (val, tableMeta) => {
      return (
        <div style={{ display: 'flex' }}>
          {tableMeta.rowIndex + 1}
        </div >
      );
    }
  }
}, {
  name: "Nama Lengkap",
  options: {
    customBodyRender: (val, tableMeta) => {
      return (
        <div style={{ display: 'flex', width: 50 }}>
          {titleCase(val)}
        </div >
      );
    }
  }
}, {
  name: "Email",
  options: {
    customBodyRender: (val, tableMeta) => {
      return (
        <div style={{ display: 'flex', width: 200 }}>
          {val}
        </div >
      );
    }
  }
}, {
  name: "Role",
  options: {
    customBodyRender: (val, tableMeta) => {
      return (
        <div style={{ display: 'flex', width: 150 }}>
          {titleCase(val)}
        </div >
      );
    }
  }
}, {
  name: "Berlaku Mulai",
  options: {
    customBodyRender: (val, tableMeta) => {
      return (
        <div style={{ display: 'flex', width: 100 }}>
          {titleCase(val)}
        </div >
      );
    }
  }
}, {
  name: "Berakhir Hingga",
  options: {
    customBodyRender: (val, tableMeta) => {
      return (
        <div style={{ display: 'flex' }}>
          {val}
        </div >
      );
    }
  }
}]

export default class UserRole extends Component {
  constructor(props) {
    super(props)
    this.state = {
      listUser: [],
      indexData: {},
      add: false,
      edit: false,
      visibleUser: true
    }
  }

  componentDidMount() {
    this.getUser()
  }

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

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

  getUser() {
    api.create().getUser().then((response) => {
      // console.log(response)
      if (response.data.status == 'success') {
        // console.log(response.data.data)
        let data = response.data.data
        let listData = data.map((item, index) => {
          return [index, item.user_id, item.fullname, item.email, item.role_name, item.company, item.status]
        })
        // console.log(listData)
        this.setState({ listUser: listData })
        // this.setState({listUser: response.data.data}, () => {
        //   console.log(this.state.listUser)
        // })
      } else {
        alert(response.data.message)
      }
      // console.log(response.data.data)
    })
  }

  searchUser() {
    let payload = {
      "keyword": this.state.search
    }
    api.create().searchUser(payload).then((response) => {
      if (response.data.status == 'success') {
        let data = response.data.data
        let listData = data.map((item, index) => {
          return [index, item.user_id, item.fullname, item.email, item.role_name, item.company, item.status]
        })
        this.setState({ listUser: listData })
      } else {
        alert(response.data.message)
      }
    })
  }

  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 = []
        isi.map((item, index) => {
          payload.push({
            id: item.id,
            fullname: item[0],
            email: item[1],
            role: item[2],
            start_date: item[3],
            end_date: item[4],
          })
        })
        let body = {
          user: payload
        }
        this.setState({ payload: body })
        api.create().checkUploadUser(body).then(response => {
          console.log(response);
          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 Ke-",
              "Nama Lengkap",
              {
                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 ?
                          <a data-tip={tableMeta.rowData[6][check].message} data-for="email">
                            <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                          </a> :
                          <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                        }
                        <ReactTooltip border={true} id="email" place="bottom" type="light" effect="solid" />
                      </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 })
                      }
                    }
                    return (
                      <div style={{ display: 'flex' }}>
                        {tableMeta.rowData[6] != null && check > -1 ?
                          <a data-tip={tableMeta.rowData[6][check].message} data-for="role">
                            <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                          </a> :
                          <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                        }
                        <ReactTooltip border={true} id="role" place="bottom" type="light" effect="solid" />
                      </div >
                    );
                  }
                }
              },
              {
                name: "Berlaku Mulai",
                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 })
                      }
                    }
                    return (
                      <div style={{ display: 'flex' }}>
                        {tableMeta.rowData[6] != null && check > -1 ?
                          <a data-tip={tableMeta.rowData[6][check].message} data-for="startdate">
                            <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                          </a> :
                          <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                        }
                        <ReactTooltip border={true} id="startdate" place="bottom" type="light" effect="solid" />
                      </div >
                    );
                  }
                }
              },
              {
                name: "Berakhir Hingga",
                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 })
                      }
                    }
                    return (
                      <div style={{ display: 'flex' }}>
                        {tableMeta.rowData[6] != null && check > -1 ?
                          <a data-tip={tableMeta.rowData[6][check].message} data-for="enddate">
                            <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                          </a> :
                          <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                        }
                        <ReactTooltip border={true} id="enddate" place="bottom" type="light" effect="solid" />
                      </div >
                    );
                  }
                }
              },
              {
                name: "",
                options: {
                  display: false
                }
              }
            ]

            this.setState({
              dataLoaded: true,
              cols: columns,
              rows: dataRow
            });
          }
        })
      }
    });
  }

  downloadFile = async () => {
    let res = await fetch(
      "https://tia.eksad.com/tia-reporting-dev/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("https://tia.eksad.com/tia-reporting-dev/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 = 'Data User.xlsx';
      a.click();
    }
  }

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

  uploadUser() {
    api.create().uploadUser(this.state.payload).then(response => {
      console.log(response)
      this.getUser()
      this.setState({ visibleUser: true })
    })
  }

  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] })}
              >
                <img src={Images.editCopy} />
              </button>
            </div >
          );
        }
      }
    }, {
      name: "ID",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex', width: 50 }}>
              {val}
            </div >
          );
        }
      }
    }, {
      name: "Nama Lengkap",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex', width: 200 }}>
              {titleCase(val)}
            </div >
          );
        }
      }
    }, {
      name: "Email",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex', width: 150 }}>
              {titleCase(val)}
            </div >
          );
        }
      }
    }, {
      name: "Role",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex', width: 100 }}>
              {titleCase(val)}
            </div >
          );
        }
      }
    }, {
      name: "Perusahaan",
      options: {
        customBodyRender: (val, tableMeta) => {
          return (
            <div style={{ display: 'flex' }}>
              {val}
            </div >
          );
        }
      }
    }, "Status"]
    return (
      <div style={{ height: this.props.height }}>
        {/* <Row> */}
        <div style={{ height: 199, backgroundColor: '#354960', width: '100%' }} />
        {this.state.visibleUser ? <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 - 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>
            {/* <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' }}>
              <button
                style={{
                  backgroundColor: 'transparent',
                  cursor: 'pointer',
                  borderColor: 'transparent',
                  margin: 5
                }}
                onClick={() => this.downloadFile()}
              >
                <img src={Images.template} />
              </button>
              <button
                style={{
                  backgroundColor: 'transparent',
                  cursor: 'pointer',
                  borderColor: 'transparent',
                  marginTop: 5,
                  marginBottom: 5,
                  marginRight: 5,
                  marginLeft: 20
                }}
                onClick={() => this.setState({ visibleUpload: true })}
              >
                <img src={Images.upload} />
              </button>
              <button
                style={{
                  backgroundColor: 'transparent',
                  cursor: 'pointer',
                  borderColor: 'transparent',
                  marginTop: 5,
                  marginBottom: 5,
                  marginRight: 5,
                  marginLeft: 20
                }}
                onClick={() => this.downloadDataTables()}
              >
                <img src={Images.download} />
              </button>
              <button
                style={{
                  backgroundColor: 'transparent',
                  cursor: 'pointer',
                  borderColor: 'transparent',
                  marginTop: 5,
                  marginBottom: 5,
                  marginRight: 5,
                  marginLeft: 20
                }}
                onClick={() => this.setState({ add: true })}
              >
                <img src={Images.add} />
              </button>
            </div>
          </div>
          <div style={{ padding: 25 }}>
            <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 })}
                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 }}>Batal</span>
                </div>
              </button>
              <button
                type="button"
                onClick={() => this.state.buttonError ? this.setState({ popupError: true }) : null}
                style={{}}
              >
                <div style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                  <span style={{ color: '#fff', fontSize: 11 }}>Simpan</span>
                </div>
              </button>
            </div>
          </div>
        }
        {this.state.add && (
          <AddUser
            onClickClose={this.closeAdd.bind(this)}
            refresh={this.getUser.bind(this)}
            data={this.state.indexData}
          />
        )}
        {this.state.edit && (
          <EditUser
            onClickClose={this.closeEdit.bind(this)}
            refresh={this.getUser.bind(this)}
            data={this.state.indexData}
          />
        )}
        {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" style={{ backgroundColor: '#51c6ea', 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 })}
                  >
                    <i className="fa fa-lg fa-times" style={{ color: 'white' }} />
                  </button>
                </div>
              </div>
              <UploadFile
                type={this.state.uploadStatus}
                percentage={this.state.percentage}
                result={this.state.result}
                acceptedFiles={["pdf"]}
                onHandle={(dt) => {
                  this.fileHandler(dt)
                  this.setState({ uploadStatus: 'idle', percentage: '0' })
                }}
                onUpload={() => this.setState({ visibleUpload: false, visibleUser: false })}
              />
            </div>
          </div>
        )}
      </div>
    );
  }
}
