import React, {Component} from 'react';
import api from "../../api";
import {format} from "date-fns";
import Constant from "../../library/Constant";
import {
    createMuiTheme,
    FormControlLabel,
    Input,
    MuiThemeProvider,
    TableCell,
    Typography,
    Paper,
    TextField,
    Snackbar
} from "@material-ui/core";
import MUIDataTable from "mui-datatables";
import {PropagateLoader} from 'react-spinners';
import {Alert} from '@material-ui/lab';
import ReactTooltip from "react-tooltip";
import Autocomplete from '@material-ui/lab/Autocomplete';
import Images from '../../assets/Images';

var ct = require("../../library/CustomTable");
const getMuiTheme = () => createMuiTheme(ct.customTable4());
const options = ct.customOptionsFixedColumnMonitoring();
const style = {
    position: "sticky",
    left: 0,
    zIndex: 101,
    background: "white",
};
const style2 = {
    position: "sticky",
    background: "white",
    zIndex: 100,
};

class RepotrCafrm extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataTable: [],
            curMonth: 0,
            curYear: 0,
            data: false
        }
        console.log(this.state.periodeMB);
        console.log(this.state.month);
    }

    async getMonth() {
        this.setState({loading: true})
        await api.create().getMonthTransaction().then(response => {
            let dateNow = new Date()
            dateNow.setMonth(dateNow.getMonth());
            let month = format(dateNow, 'MMMM')
            if (response.data) {
                if (response.data.status === "success") {
                    let data = response.data.data
                    let monthData = data.map((item) => {
                        return {
                            month_id: item.id,
                            month_value: String(item.month_name).substr(0, 3)
                        }
                    })
                    let defaultProps = {
                        options: monthData,
                        getOptionLabel: (option) => option.month_value,
                    };
                    console.log("month ");
                    console.log(defaultProps);
                    console.log(monthData[0]);
                    let index = data.findIndex((val) => val.month_name == month)
                    this.setState({
                        listMonth: defaultProps,
                        month: index == -1 ? monthData[0] : monthData[index],
                        curMonth: monthData[index]['month_id']
                    }, async () => {
                        await this.getPeriode()
                    })
                } else {
                    this.setState({alert: true, messageAlert: response.data.message, tipeAlert: 'warning'}, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({alert: true, messageAlert: response.data.message, tipeAlert: 'error'})
            }
        })
    }

    async getPeriode() {
        let currentYear = new Date().getFullYear()
        let MB = []
        for (var i = 2000; i <= currentYear; i++) {
            MB.push({name: String(i), value: i})
            if (i == currentYear) {
                MB.push({name: String(i + 1), value: i + 1})
            }
        }

        let defaultPropsMB = {
            options: MB,
            getOptionLabel: (option) => option.name,
        };

        await this.setState({
            listPeriodeMB: defaultPropsMB,
            periodeMB: MB[MB.length - 2],
            curYear: currentYear,
        }, async () => {
            await this.getStatus()
        })
    }

    async getStatus(){
        let listStatusVal = [
            {name: "All", value: 2},
            {name: "Completed", value: 1},
            {name: "Not-Yet", value: 0}
        ];

        let listStatus = {
            options: listStatusVal,
            getOptionLabel: (option) => option.name,
        };

        await this.setState({
            listStatus,
            defaultStatus : listStatusVal[0],
            curStatus: listStatusVal[0].value
        }, async () => {
            await this.getFromCallback()
        })
    }

    async getData(payload) {
        console.log("getData +1323")
        console.log(payload);
        await api.create().getMonitoringCafrm(payload).then((res) => {
            console.log(res);
            if (res.data) {
                if (res.data.status === 'success') {
                    let data = res.data.data;
                    this.setState({
                        dataTable: data,
                        data: true,
                        loading: false
                    })
                } else {
                    this.setState({
                        alert: true,
                        messageAlert: res.data.message,
                        tipeAlert: 'warning',
                        loading: false
                    }, () => {
                        if (res.data.message.includes("Someone Logged In") || res.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({alert: true, messageAlert: res.data.message, tipeAlert: 'error', loading: false})
            }
        });
    }

    async getFromCallback() {
        if (this.state.curYear >= 2000 && this.state.curMonth > 0) {
            let month = 0;
            if(this.state.curMonth >= 1 && this.state.curMonth <= 9 && this.state.curMonth.toString().length == 1){
                month = '0'+this.state.curMonth;
            }else{
                month = this.state.curMonth;
            }
        let payload = {year: this.state.curYear, month: month, status: this.state.curStatus};

            await this.getData(payload);
            console.log(`month ${this.state.curMonth} year ${this.state.curYear}`)
            this.setState({
                curMonth: month,
                loading: false
            })
        }
    }

    async downloadData() {
        let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/monitoring/export_cafrm_report?periode=${this.state.curYear}&months=${this.state.curMonth}&status=${this.state.curStatus}`
        console.log(url);
        let res = await fetch(
            `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/monitoring/export_cafrm_report?periode=${this.state.curYear}&months=${this.state.curMonth}&status=${this.state.curStatus}`
        )
        res = await res.blob()
        this.setState({ loading: false })
        if (res.size > 0) {
            let url = window.URL.createObjectURL(res);
            let a = document.createElement('a');
            a.href = url;
            a.download = `Progress Report CARFM ${this.state.curYear}-${this.state.curMonth}-${this.state.defaultStatus.name}.xlsx`;
            a.click();
        }
    }

    async componentDidMount() {
        await this.getMonth();
        // this.setState({
        //     loading: false
        // })
    }

    closeAlert() {
        this.setState({ alert: false })
    }

    render() {

        const columnMR = [
            {
                name: "company_name",
                label: "Company",
                options : {
                    customHeadRender: (columnMeta) => (
                        <TableCell key={columnMeta.index} style={{ ...style, top: 0, zIndex: 103, backgroundColor: "#1c71b8", width: 200, borderRight: "1px #fff solid", borderBottom: "1px #fff solid", }}>
                            <Typography style={{ color: "white", fontSize: 12, fontWeight: "bold", textAlign: "center" }}>{columnMeta.label}</Typography>
                        </TableCell>
                    ),
                    setCellProps: () => ({ style }),
                    customBodyRender: (val) => {
                        return <div style={{ width: 300, textAlign: 'left', paddingLeft: 20 }}>{val}</div>;
                    },
                }
            },
            {
                name: 'internal_audit',
                label: "Internal Audit",
                options : {
                    customHeadRender : (columnMeta) => (
                        <TableCell key={columnMeta.index} style={{ ...style, top: 0, zIndex: 103, backgroundColor: "#1c71b8", width: 200, borderRight: "1px #fff solid", borderBottom: "1px #fff solid", }}>
                            <Typography style={{ color: "white", fontSize: 12, fontWeight: "bold", textAlign: "center" }}>{columnMeta.label}</Typography>
                        </TableCell>
                    ),
                    setCellProps: () => ({style2}),
                    customBodyRender: (val) => {
                        return (
                            <div className="column-1" style={{ placeSelf: 'center', textAlign: 'center', padding: 5 }}>
                                <div style={{ textAlign: 'center' }}>{val}</div>
                            </div>
                        )
                    }
                }
            },
            {
                name: 'anti_fraud',
                label: "Anti Fraud",
                options : {
                    customHeadRender : (columnMeta) => (
                        <TableCell key={columnMeta.index} style={{ ...style, top: 0, zIndex: 103, backgroundColor: "#1c71b8", width: 200, borderRight: "1px #fff solid", borderBottom: "1px #fff solid", }}>
                            <Typography style={{ color: "white", fontSize: 12, fontWeight: "bold", textAlign: "center" }}>{columnMeta.label}</Typography>
                        </TableCell>
                    ),
                    setCellProps: () => ({style2}),
                    customBodyRender: (val) => {
                        return (
                            <div className="column-1" style={{ placeSelf: 'center', textAlign: 'center', padding: 5 }}>
                                <div style={{ textAlign: 'center' }}>{val}</div>
                            </div>
                        )
                    }
                }
            },
            {
                name: 'risk_management',
                label: "Risk Management",
                options : {
                    customHeadRender : (columnMeta) => (
                        <TableCell key={columnMeta.index} style={{ ...style, top: 0, zIndex: 103, backgroundColor: "#1c71b8", width: 200, borderRight: "1px #fff solid", borderBottom: "1px #fff solid", }}>
                            <Typography style={{ color: "white", fontSize: 12, fontWeight: "bold", textAlign: "center" }}>{columnMeta.label}</Typography>
                        </TableCell>
                    ),
                    setCellProps: () => ({style2}),
                    customBodyRender: (val) => {
                        return (
                            <div className="column-1" style={{ placeSelf: 'center', textAlign: 'center', padding: 5 }}>
                                <div style={{ textAlign: 'center' }}>{val}</div>
                            </div>
                        )
                    }
                }
            }
        ];

        const loadingComponent = (
            <div style={{
                position: 'fixed',
                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', minHeight: this.props.height}}>
                <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 className={"main-color"}
                         style={{height: 78, display: 'flex', alignItems: 'center', paddingLeft: 20}}>
                        <Typography style={{fontSize: '16px', color: 'white'}}>Report Status Progress
                            Monitoring CAFRM</Typography>
                    </div>
                    <div style={{padding: 20, width: '100%'}}>
                        <Paper style={{paddingTop: 10, paddingBottom: 50}}>
                            <div style={{borderBottom: 'solid 1px #c4c4c4'}}>
                                <Typography style={{fontSize: '12px', color: '#4b4b4b', margin: 10}}>Report Status Progress CAFRM</Typography>
                            </div>

                            {this.state.curMonth > 0 && this.state.curYear > 2000 && !this.state.loading && (
                                <div style={{minWidth: 'max-content', padding: '20px 20px 0px 20px'}}>
                                    <div style={{marginTop: 15, display: 'flex'}}>
                                        <Autocomplete
                                            {...this.state.listPeriodeMB}
                                            id="periode"
                                            onChange={(event, newInputValue) => this.setState({
                                                periodeMB: newInputValue,
                                                curYear: newInputValue['value'],
                                                loading: true,
                                            }, async () => {
                                                await this.getFromCallback()
                                            })}
                                            disableClearable
                                            style={{minWidth: 210, marginRight: 20}}
                                            renderInput={(params) => <TextField {...params} label="Periode" margin="normal" style={{marginTop: 7}}/>}
                                            defaultValue={this.state.periodeMB}
                                            value={this.state.periodeMB}
                                        />
                                        <Autocomplete
                                            {...this.state.listMonth}
                                            id="month"
                                            onChange={(event, newInputValue) => this.setState({
                                                month: newInputValue,
                                                curMonth: newInputValue['month_id'],
                                                loading: true
                                            }, async () => {
                                                await this.getFromCallback()
                                            })}
                                            disableClearable
                                            style={{minWidth: 210, marginRight: 20}}
                                            renderInput={(params) => <TextField {...params} label="Month" margin="normal" style={{marginTop: 7}}/>}
                                            value={this.state.month}
                                        />
                                        <Autocomplete
                                            {...this.state.listStatus}
                                            id="status"
                                            onChange={(event, newInputValue) => this.setState({
                                                defaultStatus: newInputValue,
                                                curStatus: newInputValue['value'],
                                                loading: true
                                            }, async () => {
                                                await this.getFromCallback()
                                            })}
                                            disableClearable
                                            style={{minWidth: 210, marginRight: 20}}
                                            renderInput={(params) => <TextField {...params} label="Status" margin="normal" style={{marginTop: 7}}/>}
                                            value={this.state.defaultStatus}
                                        />

                                    </div>
                                </div>
                            )}

                            <div style={{marginTop: 20, marginBottom: 20}}>
                                <div style={{
                                    display: 'flex',
                                    justifyContent: 'space-between',
                                    padding: '0px 20px 10px 20px'
                                }}>
                                    <div></div>
                                    {this.state.curMonth > 0 && this.state.curYear > 2000 && !this.state.loading && (
                                    <div style={{
                                        width: '50%',
                                        justifyContent: 'flex-end',
                                        display: 'flex',
                                        flexFlow: 'wrap'
                                    }}>
                                        <a data-tip={'Download'} data-for="download">
                                            <button
                                                style={{
                                                    backgroundColor: 'transparent',
                                                    cursor: 'pointer',
                                                    borderColor: 'transparent',
                                                    margin: 5,
                                                    outline: 'none'
                                                }}
                                                onClick={() => this.setState({loading: true}, () => {
                                                    setTimeout(() => {
                                                        this.downloadData()
                                                    }, 100);
                                                })}
                                            >
                                                <img src={Images.download}/>
                                            </button>
                                        </a>
                                        <ReactTooltip border={true} id="download" place="bottom" type="light"
                                                      effect="solid"/>
                                    </div>
                                    )}
                                </div>
                                {this.state.loading && loadingComponent}
                                {this.state.curMonth > 0 && this.state.curYear > 2000 && !this.state.loading && (
                                    <div style={{
                                        padding: "0px 20px 20px 20px",
                                        width: this.props.width - (this.props.open === true ? 350 : 100)
                                    }}>
                                        <MuiThemeProvider theme={getMuiTheme()}>
                                            <MUIDataTable
                                                data={this.state.dataTable}
                                                columns={columnMR}
                                                options={options}
                                            />
                                        </MuiThemeProvider>
                                    </div>
                                )}
                            </div>
                        </Paper>
                    </div>
                </div>
            </div>
        );
    }
}

export default RepotrCafrm;