import React, { Component } from 'react';
import { Typography, MuiThemeProvider, createMuiTheme, Paper } from '@material-ui/core';
import MUIDataTable from "mui-datatables";
import Images from '../assets/Images';
import DonutChart from 'react-d3-donut';
import Constant from '../library/Constant';
import api from '../api';
import { Link } from 'react-router-dom';
import { PropagateLoader } from 'react-spinners';
import { titleCase } from '../library/Utils';

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

class HomePage extends Component {
    constructor(props) {
        super(props)
        this.state = {
            userData: null,
            listDashboard: [],
            listMasterBudget: [
                { nama: 'Triputra Agro Persada', status: 'complete' },
                { nama: 'Puninar Infinite Raya', status: 'complete' },
                { nama: 'Dharma Group', status: 'overdue' },
                { nama: 'Daya Group', status: 'open' },
            ],
            isApprover: true,
            listSubcoMB: [],
            valueSubmit: 0,
            listdmb: [],
            dataTableMB: [],
            loading: false
        }
    }

    componentDidMount() {
        this.setState({ loading: true })
        let userId = localStorage.getItem(Constant.USER)
        api.create().getDetailUser(userId).then((response) => {
            if (response.data) {
                if (response.data.status === 'success') {
                    this.setState({ userData: response.data.data }, () => {
                        console.log(this.state.userData)
                    })
                }
            }
        })
        // api.create().checkApprover().then(response => {
        //     console.log(response);
        //     if (response.data.data.is_approver === true) {
        //         this.setState({ isApprover: true }, () =>
        //             this.getDashboard())
        //     } else {
        //         this.setState({ isApprover: false })
        //     }
        // })
        this.getApprMat()
        this.getListUserSubco()
        this.getDashboardMB()
        this.getDashboard()
    }

    componentDidUpdate() {
        window.onpopstate = e => {
            //your code...
            this.props.selectIndex('Home')
        }
    }

    getListUserSubco() {
        api.create().getDashboardUser().then(response => {
            console.log(response);
            let valueSubmit = 0
            if (response.data) {
                if (response.data.status === "success") {
                    response.data.data.map((item, index) => {
                        if (item.is_submit === true) {
                            valueSubmit += 1
                        }
                    })
                    this.setState({
                        listSubcoMB: response.data.data,
                        valueSubmit,
                        loading: false
                    })
                }
            }
        })
    }

    getDashboard() {
        let listDashboard = []
        api.create().getDashboard().then((response) => {
            console.log(response);
            if (String(response.data.status).toLocaleLowerCase() == 'success') {
                let data = response.data.data
                data.map((item, index) => {
                    let statusConvert = item.status == 'approval_review'? 'Waiting For Review' : item.status == 'approval_proccess'? 'Waiting For Approval' : titleCase(item.status) 
                    listDashboard.push([index + 1, item.approval_id, item.company_name, `${item.type_report} - ${item.periode}`, item.revision, item.status, statusConvert])
                })
                this.setState({ listDashboard, rawData: response.data.data })
            }
        })
    }

    getApprMat() {
        this.setState({loading: true})
        api.create().getAM().then((response) => {
            console.log(response);
            let actAM = response.data.data.map((item, index) => {
                if (String(item.status).toLocaleLowerCase() == 'active') {
                    return item

                }
            })
            let userId = localStorage.getItem(Constant.USER)
            let indexId = actAM.findIndex((val) => val.user_id == userId)
            if (indexId === -1) {
                this.setState({ isApprover: false })
                this.getListUserSubco()
            }
            this.getDashboardMB()
            console.log(actAM)
            this.setState({loading: false})
        })
    }

    getDashboardMB() {
        api.create().getDashboardMB().then((response) => {
            console.log(response)
            if (String(response.data.status).toLocaleLowerCase() == 'success') {
                let data = response.data.data
                let listdmb = data.sort((a, b) => a.company_id - b.company_id).map((item, index) => {
                    return [
                        item.company_name,
                        item.master_budget,
                        item.operating_indicator
                    ]
                })
                this.setState({ dataTableMB: listdmb, loading: false })
            }
        })
    }

    render() {
        const columns = ["#", "ID", "Company", "Report Type", "Revision", 
        {
            name: "",
            options: {
                display: false
            }
        }, 'Status', {
            name: "Action",
            options: {
                customBodyRender: (val, tableMeta) => {
                    // console.log(tableMeta);
                    return (
                        <div style={{ display: 'flex' }}>
                            <Link to={{
                                pathname: `/home/master-budget/`,
                                state: {
                                    userType: 'approver',
                                    rawData: this.state.rawData[tableMeta.rowIndex]
                                }
                            }}>
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        marginRight: 10
                                    }}
                                    onClick={() => null}
                                >
                                    <img src={Images.editCopy2} />
                                </button>
                            </Link>
                        </div >
                    );
                }
            }
        }]
        const data = [
            ["1", "TRIPUTRA AGRO PERSADA", "Laporan Bulanan - September 2020", "1 (20 Oktober 2020)", "Belum Disetujui"],
            ["2", "DAYA GROUP", "Laporan Bulanan - September 2020", "1 (20 Oktober 2020)", "Belum Disetujui"],
            ["3", "PUNINAR INFINITE RAYA", "Budget Tahunan 2021", "0 (20 Oktober 2020)", "Belum Disetujui"],
            ["4", "DHARMA GROUP", "Laporan Bulanan - September 2020", "0 (20 Oktober 2020)", "Belum Disetujui"],
            ["5", "PUNINAR INFINITE RAYA", "Budget Tahunan 2021", "0 (20 Oktober 2020)", "Belum Disetujui"],
        ]
        const options = {
            filter: false,
            sort: false,
            responsive: "scroll",
            print: false,
            download: false,
            selectableRows: false,
            viewColumns: false,
            rowsPerPage: 5,
            search: false
        }

        const columnsMB = ["Company", "Master Budget & CAT", "Operating Indicator"]

        const dataChart = [{
            count: 90,
            color: '#5198ea',
            name: 'My name',
        }, {
            count: 10,
            color: '#ffd600',
            name: 'name',
        }]
        const dataChart2 = [{
            count: 90,
            color: '#f65a4c',
            name: 'My name',
        }, {
            count: 10,
            color: '#5198ea',
            name: 'name',
        }]
        const dataChart3 = [{
            count: 90,
            color: '#4caf51',
            name: 'My name',
        }, {
            count: 10,
            color: '#f65a4c',
            name: 'name',
        }]
        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={{ flex: 1, backgroundColor: '#f8f8f8' }}>
                {this.state.loading && loadingComponent}
                {this.state.isApprover === true ?
                    <div>
                        <div className={"main-color"} style={{ height: 78, flex: 1, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                            <Typography style={{ fontSize: '24px', color: 'white' }}>{this.state.userData === null ? '' : `Welcome, ${this.state.userData.fullname} !`}</Typography>
                        </div>
                        <div style={{ flex: 1, padding: 20, width: '100%' }}>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ color: '#656565', fontSize: '16px', fontWeight: 'bold' }}>Waiting Your Approval</Typography>
                            </div>

                        </div>
                        <div style={{ flex: 1, padding: 20, width: '100%' }}>
                            <div>
                                <MuiThemeProvider theme={getMuiTheme()}>
                                    <MUIDataTable
                                        data={this.state.listDashboard}
                                        columns={columns}
                                        options={options}
                                    />
                                </MuiThemeProvider>
                            </div>
                            <div style={{ marginTop: 20 }}>
                                <Typography style={{ color: '#656565', fontSize: '16px', fontWeight: 'bold' }}>Master Budget & CAT</Typography>
                                <div style={{ marginTop: 10, width: '100%' }}>
                                    <MuiThemeProvider theme={getMuiTheme()}>
                                        <MUIDataTable
                                            data={this.state.dataTableMB}
                                            columns={columnsMB}
                                            options={options}
                                        />
                                    </MuiThemeProvider>
                                </div>
                            </div>
                            {/* <div style={{ marginTop: 20 }}>
                                <Typography style={{ color: '#656565', fontSize: '16px', fontWeight: 'bold' }}>Status Laporan</Typography>
                                <div style={{ marginTop: 10, display: 'flex' }}>
                                    <div style={{ width: 280, height: 400, padding: 20, backgroundColor: 'white', borderRadius: 6, border: 'solid 1px #c4c4c4', marginRight: 25 }}>
                                        <Typography style={{ color: '#4b4b4b', fontSize: '24px', fontWeight: 'bold' }}>Budget Tahunan - 2021</Typography>
                                        <div style={{ textAlign: 'center' }}>
                                            <DonutChart
                                                innerRadius={70}
                                                outerRadius={100}
                                                transition={true}
                                                pieClass="pie1"
                                                displayTooltip={true}
                                                strokeWidth={3}
                                                data={dataChart} />
                                        </div>
                                        <div style={{ display: 'flex', width: '100%', marginTop: 10 }}>
                                            <div style={{ width: '33%' }}>
                                                <Typography style={{ color: '#656565', fontSize: '15px', textAlign: 'left' }}>Submit</Typography>
                                                <Typography style={{ color: '#656565', fontSize: '20px', textAlign: 'left' }}>92.8 %</Typography>
                                                <div style={{ display: 'flex' }} >
                                                    <img src={Images.red} />
                                                    <Typography style={{ color: '#656565', fontSize: '14px', textAlign: 'left' }}>-0.6%</Typography>
                                                </div>
                                            </div>
                                            <div style={{ width: '33%' }}>
                                                <Typography style={{ color: '#656565', fontSize: '15px', textAlign: 'left' }}>On Time</Typography>
                                                <Typography style={{ color: '#656565', fontSize: '20px', textAlign: 'left' }}>6.1 %</Typography>
                                                <div style={{ display: 'flex' }} >
                                                    <img src={Images.green} />
                                                    <Typography style={{ color: '#656565', fontSize: '14px', textAlign: 'left' }}>0.7%</Typography>
                                                </div>

                                            </div>
                                            <div style={{ width: '33%' }}>
                                                <Typography style={{ color: '#656565', fontSize: '15px', textAlign: 'left' }}>Overdue</Typography>
                                                <Typography style={{ color: '#656565', fontSize: '20px', textAlign: 'left' }}>1.1 %</Typography>
                                                <div style={{ display: 'flex' }} >
                                                    <img src={Images.green} />
                                                    <Typography style={{ color: '#656565', fontSize: '14px', textAlign: 'left' }}>0.1%</Typography>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div style={{ width: 280, height: 400, padding: 20, backgroundColor: 'white', borderRadius: 6, border: 'solid 1px #c4c4c4', marginRight: 25 }}>
                                        <Typography style={{ color: '#4b4b4b', fontSize: '24px', fontWeight: 'bold' }}>Laporan Bulanan - Oct 2020</Typography>
                                        <div style={{ textAlign: 'center' }}>
                                            <DonutChart
                                                innerRadius={70}
                                                outerRadius={100}
                                                transition={true}
                                                pieClass="pie5"
                                                displayTooltip={true}
                                                strokeWidth={3}
                                                data={dataChart2}
                                            />
                                        </div>
                                        <div style={{ display: 'flex', width: '100%', marginTop: 10 }}>
                                            <div style={{ width: '33%' }}>
                                                <Typography style={{ color: '#656565', fontSize: '15px', textAlign: 'left' }}>Submit</Typography>
                                                <Typography style={{ color: '#656565', fontSize: '20px', textAlign: 'left' }}>92.8 %</Typography>
                                                <div style={{ display: 'flex' }} >
                                                    <img src={Images.red} />
                                                    <Typography style={{ color: '#656565', fontSize: '14px', textAlign: 'left' }}>-0.6%</Typography>
                                                </div>
                                            </div>
                                            <div style={{ width: '33%' }}>
                                                <Typography style={{ color: '#656565', fontSize: '15px', textAlign: 'left' }}>On Time</Typography>
                                                <Typography style={{ color: '#656565', fontSize: '20px', textAlign: 'left' }}>6.1 %</Typography>
                                                <div style={{ display: 'flex' }} >
                                                    <img src={Images.green} />
                                                    <Typography style={{ color: '#656565', fontSize: '14px', textAlign: 'left' }}>0.7%</Typography>
                                                </div>

                                            </div>
                                            <div style={{ width: '33%' }}>
                                                <Typography style={{ color: '#656565', fontSize: '15px', textAlign: 'left' }}>Overdue</Typography>
                                                <Typography style={{ color: '#656565', fontSize: '20px', textAlign: 'left' }}>1.1 %</Typography>
                                                <div style={{ display: 'flex' }} >
                                                    <img src={Images.green} />
                                                    <Typography style={{ color: '#656565', fontSize: '14px', textAlign: 'left' }}>0.1%</Typography>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div style={{ width: 280, height: 400, padding: 20, backgroundColor: 'white', borderRadius: 6, border: 'solid 1px #c4c4c4', }}>
                                        <Typography style={{ color: '#4b4b4b', fontSize: '24px', fontWeight: 'bold', height: 71 }}>Lainnya</Typography>
                                        <div style={{ textAlign: 'center' }}>
                                            <DonutChart
                                                innerRadius={70}
                                                outerRadius={100}
                                                transition={true}
                                                pieClass="pie2"
                                                displayTooltip={true}
                                                strokeWidth={3}
                                                data={dataChart3}
                                            />
                                        </div>
                                        <div style={{ display: 'flex', width: '100%', marginTop: 10 }}>
                                            <div style={{ width: '33%' }}>
                                                <Typography style={{ color: '#656565', fontSize: '15px', textAlign: 'left' }}>Submit</Typography>
                                                <Typography style={{ color: '#656565', fontSize: '20px', textAlign: 'left' }}>92.8 %</Typography>
                                                <div style={{ display: 'flex' }} >
                                                    <img src={Images.red} />
                                                    <Typography style={{ color: '#656565', fontSize: '14px', textAlign: 'left' }}>-0.6%</Typography>
                                                </div>
                                            </div>
                                            <div style={{ width: '33%' }}>
                                                <Typography style={{ color: '#656565', fontSize: '15px', textAlign: 'left' }}>On Time</Typography>
                                                <Typography style={{ color: '#656565', fontSize: '20px', textAlign: 'left' }}>6.1 %</Typography>
                                                <div style={{ display: 'flex' }} >
                                                    <img src={Images.green} />
                                                    <Typography style={{ color: '#656565', fontSize: '14px', textAlign: 'left' }}>0.7%</Typography>
                                                </div>

                                            </div>
                                            <div style={{ width: '33%' }}>
                                                <Typography style={{ color: '#656565', fontSize: '15px', textAlign: 'left' }}>Overdue</Typography>
                                                <Typography style={{ color: '#656565', fontSize: '20px', textAlign: 'left' }}>1.1 %</Typography>
                                                <div style={{ display: 'flex' }} >
                                                    <img src={Images.green} />
                                                    <Typography style={{ color: '#656565', fontSize: '14px', textAlign: 'left' }}>0.1%</Typography>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div> */}
                        </div>
                    </div>
                    :
                    <div>
                        <div className={"main-color"} style={{ height: 78, flex: 1, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                            <Typography style={{ fontSize: '24px', color: 'white' }}>{this.state.userData === null ? '' : `Welcome, ${this.state.userData.fullname} !`}</Typography>
                        </div>
                        <div style={{ flex: 1, padding: 20, width: '100%' }}>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ color: '#656565', fontSize: '16px', fontWeight: 'bold' }}>Tasks to be Complete</Typography>
                            </div>
                        </div>
                        <div style={{ flex: 1, padding: 20, width: '100%' }}>
                            <Paper style={{ width: 450, padding: 20, borderRadius: 10 }}>
                                <Typography style={{ fontWeight: 'bold', textDecorationLine: 'underline' }}>{`Master Budget ${this.state.valueSubmit}/${this.state.listSubcoMB.length}`}</Typography>
                                {this.state.listSubcoMB.map((item, index) => {
                                    return (
                                        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, paddingLeft: 10 }}>
                                            <div style={{ display: 'flex' }}>
                                                <img src={item.is_submit === true ? Images.dotDone : item.is_overdue === true ? Images.dotOverdue : Images.dotOpen} />
                                                <Link to={{
                                                    pathname: `/home/master-budget/`,
                                                    state: {
                                                        userType: 'user',
                                                        rawData: item
                                                    }
                                                }}>
                                                    <button
                                                        style={{
                                                            backgroundColor: 'transparent',
                                                            cursor: 'pointer',
                                                            borderColor: 'transparent',
                                                            margin: 5,
                                                            outline: 'none'
                                                        }}>
                                                        <Typography style={{ marginLeft: 10, color: '#5198ea', fontSize: 13 }}>{item.company_name}</Typography>
                                                    </button>
                                                </Link>
                                            </div>
                                            {item.is_overdue && (
                                                <div style={{ backgroundColor: '#f65a4c', paddingRight: 5, paddingLeft: 5, borderRadius: 5, alignSelf: 'center' }}>
                                                    <Typography style={{ fontSize: 11, color: '#fff' }}>Overdue</Typography>
                                                </div>
                                            )}
                                        </div>
                                    )
                                })}
                            </Paper>
                        </div>
                    </div>
                }
            </div>
        );

    }
}

export default HomePage;
