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 UploadFile from "../../library/Upload";
import MUIDataTable from "mui-datatables";
import CreateUnitBisnis from "./formUnitBisnis/CreateUnitBisnis";
import { TextField, InputBase } from "@material-ui/core";
import { ExcelRenderer } from 'react-excel-renderer';
import api from "../../api";
import { isThisSecond } from "date-fns";

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

export default class UnitBisnis extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visibleCreate: false,
            visibleEdit: false,
            dataTable: [],
            listData: [],
            data: [],
            search: "",
            visibleUnitBisnis: true,
            cols: null,
            rows: null,
            dataLoaded: false
        }
        this.fileHandler = this.fileHandler.bind(this);
    }

    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(1)
                // let body = isi.map((item) => {
                //     return {
                //         item
                //     ]
                // })
                console.log(JSON.stringify(isi));
                this.setState({
                    dataLoaded: true,
                    cols: judul,
                    rows: isi
                });
            }
        });
    }

    componentDidMount() {
        this.getData()
    }

    getData() {
        api.create().getUnitBisnis().then((response) => {
            console.log(response)
            if (response.data.status == 'success') {
                let data = response.data.data
                let listData = data.map((item, index) => {
                    return [index, item.business_unit_id, item.business_unit_name, item.status]
                })
                this.setState({ dataTable: listData, listData: response.data.data })
            } else {
                alert(response.data.message)
            }
        })
    }

    openPopUp(index, type) {
        if (type === 'edit') {
            this.setState({
                selectIndex: index,
                visibleEdit: true
            })
        } else {
            this.setState({
                data: this.state.listData[index],
                visibleCreate: true
            })
        }
    }

    handleInputChange(e) {
        this.setState({ search: e })
        let body = {
            "keyword": e
        }
        api.create().searchUnitBisnis(body).then(response => {
            // console.log(response.data);
            if (response.data.status == 'success') {
                let data = response.data.data
                let listData = data.map((item, index) => {
                    return [index, item.business_unit_id, item.business_unit_name, item.status]
                })
                this.setState({ dataTable: listData, listData: response.data.data })
            } else {
                alert(response.data.message)
            }
        })
    }

    updateUnitBisnis = (payload) => {
        this.setState({ visibleEdit: false })
        api.create().updateUnitBisnis(payload).then(response => {
            if (response.data.status == 'success') {
                this.getData()
            } else {
                alert(response.data.message)
            }
        })
    }

    createUnitBisnis = (payload) => {
        this.setState({ visibleCreate: false })
        api.create().createUnitBisnis(payload).then(response => {
            if (response.data.status == 'success') {
                this.getData()
            } else {
                alert(response.data.message)
            }
        })
    }

    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.openPopUp(tableMeta.rowIndex, 'edit')}
                            >
                                <img src={Images.editCopy} />
                            </button>
                        </div >
                    );
                }
            }
        }, {
            name: "ID",
            options: {
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>
                            <span style={{ color: tableMeta.rowData[3] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
                        </div >
                    );
                }
            }
        }, {
            name: "Unit Bisnis",
            options: {
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>
                            <span style={{ color: tableMeta.rowData[3] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
                        </div >
                    );
                }
            }
        }, {
            name: "Status",
            options: {
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>
                            <span style={{ color: tableMeta.rowData[3] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
                        </div >
                    );
                }
            }
        }]
        const data = [
            ["", "1", "Agribisnis", "Aktif"],
            ["", "2", "Manufacturing", "Aktif"],
            ["", "3", "Trading", "Aktif"],
            ["", "4", "Service", "Non Aktif"],
            ["", "-", "-", "-"],
        ]
        return (
            <div style={{ height: this.props.height }}>
                {/* <Row> */}

                <div style={{ height: 199, backgroundColor: '#354960', width: '100%' }} />
                {this.state.visibleUnitBisnis === true ?
                    <div>
                        <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingRight: 25, paddingLeft: 25, marginTop: -150 }}>
                            <label style={{ color: 'white', fontSize: 16, alignSelf: 'center', width: '20%', }}>Master Data - Unit Bisnis</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.handleInputChange(e.target.value)}
                                    inputProps={{ 'aria-label': 'naked' }}
                                />
                                {/* <input type="text" value={this.state.search} onChange={(e)=> this.setState({ search: e.target.value})} style={{ width: '100%'}} /> */}
                            </div>
                            <div style={{ width: '30%', justifyContent: 'space-around', display: 'flex', flexFlow: 'wrap' }}>
                                <img src={Images.template} />
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent'
                                    }}
                                    onClick={() => this.setState({ visibleUpload: true })}
                                >
                                    <img src={Images.upload} />
                                </button>
                                <img src={Images.download} />
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent'
                                    }}
                                    onClick={() => this.setState({ visibleCreate: true })}
                                >
                                    <img src={Images.add} />
                                </button>
                            </div>
                        </div>
                        <div style={{ padding: 25 }}>
                            <MuiThemeProvider theme={getMuiTheme()}>
                                <MUIDataTable
                                    theme={getMuiTheme()}
                                    data={this.state.dataTable}
                                    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={options2}
                                    />
                                </MuiThemeProvider>
                            )}
                        </div>
                        <div style={{ display: 'flex', width: '100%', placeContent: 'flex-end', padding: 20 }}>
                            <button
                                type="button"
                                onClick={() => this.setState({ visibleUnitBisnis: 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>
                            <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>
                        </div>
                    </div>
                }

                {this.state.visibleCreate && (
                    <CreateUnitBisnis
                        onClickClose={() => this.setState({ visibleCreate: false })}
                        type={"create"}
                        createUnitBisnis={this.createUnitBisnis.bind(this)}
                    />
                )}

                {this.state.visibleEdit && (
                    <CreateUnitBisnis
                        type={"edit"}
                        onClickClose={() => this.setState({ visibleEdit: false })}
                        data={this.state.listData[this.state.selectIndex]}
                        updateUnitBisnis={this.updateUnitBisnis.bind(this)}
                    />
                )}
                {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, visibleUnitBisnis: false })}
                            />
                        </div>
                    </div>
                )}
            </div>
        );
    }
}
