import React, { Component } from 'react'
import { Typography, MenuItem, TextField, AppBar, Paper, Tabs, Tab, Snackbar, withStyles } from '@material-ui/core'
import ExceutiveScoreboard from './ExceutiveScoreboard'
import StrategiMap from './StrategiMap'
import KPIs from './KPIs'
import api from '../../api'
import { Autocomplete } from '@material-ui/lab'
import { PropagateLoader } from 'react-spinners'
import MuiAlert from '@material-ui/lab/Alert';
import Constant from '../../library/Constant'
import { titleCase } from '../../library/Utils'
import { format } from 'date-fns';

const Alert = withStyles({
})((props) => <MuiAlert elevation={6} variant="filled" {...props} />);

export default class DashboardCAT extends Component {
    constructor(props) {
        super(props)
        this.state = {
            periode: '2020',
            perusahaan: 'TAP Group',
            tab: 0,
            lastPeriod: '',
            listCompany: null,
            company: null,
            listPeriode: null,
            periode: null,
            listMonth: null,
            month: null,
            loading: true,
            dataDashboard: [],
            selectedKPI: [],
            listKPI: [],
            selectedMonth: [],
            rawData: null
        }
    }

    componentDidMount() {
        console.log(this.props)
        // localStorage.removeItem(Constant.DATACAT)
        this.props.selectIndex('CAT Dashboard')
        let dataStorageCAT = localStorage.getItem(Constant.DATACAT)
        if (this.props.location.state !== undefined) {
            if (dataStorageCAT != 'datacat' && dataStorageCAT != null) {
                this.setState({ selectedKPI: JSON.parse(dataStorageCAT).listKPI }, () => {
                    console.log(dataStorageCAT)
                    // console.log(this.props.location.state.rawData.companyId)
                    console.log(this.state.selectedKPI)
                    this.setState({ userType: this.props.location.state.userType, intent: 'Home', rawData: this.props.location.state.rawData}, () => {
                        this.getDetailUser()
                    })
                })

            } else {
                this.setState({ userType: this.props.location.state.userType, intent: 'Home', rawData: this.props.location.state.rawData }, () => {
                    this.getDetailUser()
                })
            }

            // console.log(this.state.selectedKPI)
            // console.log(dataStorageCAT)
            // console.log(this.state.company.company_id)
            // this.setState({ userType: this.props.location.state.userType, intent: 'Home', rawData: this.props.location.state.rawData, selectedKPI: this.state.selectedKPI.length == 0? [] : ((dataStorageCAT != 'datacat' && dataStorageCAT != null) ? (dataStorageCAT.companyId == this.state.company.company_id? JSON.parse(dataStorageCAT).listKPI : []) : [])}, () => {
            //     this.getDetailUser()
            // })
        } else {
            this.getDetailUser()
        }
    }

    getDetailUser() {
        console.log(this.state.rawData)
        let userId = localStorage.getItem(Constant.USER)
        api.create().getDetailUser(userId).then((response) => {
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        this.getRole(response.data.data.role_id)
                        this.setState({ userCompany: response.data.data.company }, () => {
                            this.getCompanyActive()
                        })
                    }
                    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' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
            //     }
            // }
        })
    }

    getRole(id) {
        api.create().getDetailRole(id).then((response) => {
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        // this.setState({ tempData: response.data.data, privileges: response.data.data.privileges })
                        // // // console.log(response.data.data)
                        if (String(response.data.data.role_name).toLocaleLowerCase() == 'superadmin') {
                            this.setState({ isAdmin: true })
                        }
                    } 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' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getCompanyActive() {
        api.create().getPerusahaanActive().then((response) => {
            console.log(response);
            if (response.data) {
                if (response.data.status === 'success') {
                    let data = response.data.data
                    let comID = this.state.rawData != null ? this.state.rawData.companyId : 0
                    // console.log(comID)
                    let companyData = data.map((item) => {
                        return {
                            company_id: item.company_id,
                            company_name: item.company_name,
                        }
                    })

                    let arrayBaru = []
                    this.state.userCompany.map((item, index) => {
                        let indexID = companyData.findIndex((val) => val.company_id == item)
                        if (indexID !== -1) {
                            arrayBaru.push(companyData[indexID])
                        }
                    })

                    let defaultProps = {
                        options: arrayBaru.sort((a, b) => a.company_name.localeCompare(b.company_name)),
                        getOptionLabel: (option) => titleCase(option.company_name),
                    };
                    let index = arrayBaru.findIndex((val) => val.company_id == comID)

                    this.setState({ listCompany: defaultProps, company: arrayBaru.length < 1 ? companyData[0] : (index == -1 ? arrayBaru[0] : arrayBaru[index]) }, () => {
                        let dataStorageCAT = localStorage.getItem(Constant.DATACAT)
                        let userID = localStorage.getItem(Constant.USER)
                        if (dataStorageCAT != 'datacat' && dataStorageCAT != null) {
                            let arrayStorage = JSON.parse(dataStorageCAT)
                            let indexListKPI = arrayStorage.findIndex((val) => val.userID == userID)
                            let selectedKPI = []
                            let indexListKPIDetail = -1
                            if (indexListKPI != -1) {
                                indexListKPIDetail = arrayStorage[indexListKPI].listKPI.findIndex((val) => val.companyId == this.state.company.company_id)
                                if (indexListKPIDetail != -1) {
                                    selectedKPI = arrayStorage[indexListKPI].listKPI[indexListKPIDetail].list
                                }
                            }
                            this.setState({ selectedKPI })
                        }
                        this.getLastPeriod()
                    })
                } 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.problem, tipeAlert: 'error', listCompany: null, company: null })
            }
        })
    }

    getLastPeriod() {
        console.log(this.state.company)
        api.create().getLastPeriod(this.state.company.company_id).then(response => {
            console.log(response);
            if (response.data.status === "success") {
                this.setState({ lastPeriod: response.data.data.last_periode, latestPeriode: response.data.data.latest_periode }, () => {
                    console.log(this.state.lastPeriod)
                    this.getPeriode()
                })
            }
        })
    }

    getPeriode() {
        api.create().getPeriodeTransaction().then(response => {
            // let dateNow = new Date
            console.log(response)
            // let year = this.state.rawData ? this.state.rawData.periode : format(dateNow, 'yyyy')
            let currentYear = new Date().getFullYear()
            // // // console.log(currentYear)
            if (response.data) {
                if (response.data.status === "success") {
                    let data = []
                    console.log(response.data.data)
                    console.log(this.state.lastPeriod)
                    let periodeID = this.state.rawData != null ? this.state.rawData.periode : 0
                    response.data.data.map((item) => {
                        if (this.state.isApprover) {
                            if (item >= 2000 && item <= (Number(currentYear) + 1)) {
                                data.push(item)
                            }
                        } else {
                            if ((Number(item) >= 2000) && (Number(item) == this.state.lastPeriod || Number(item) < this.state.lastPeriod)) {
                                data.push(item)
                            }
                        }
                    })
                    let periodeData = data.map((item) => {
                        return {
                            periode: item,
                        }
                    })
                    let defaultProps = {
                        options: periodeData.sort((a, b) => a.periode - b.periode),
                        getOptionLabel: (option) => option.periode,
                    };
                    let periode = (this.state.lastPeriod == "" ? String(Number(currentYear) + 1) : this.state.lastPeriod)
                    let index = periodeData.sort((a, b) => a.periode - b.periode).findIndex((val) => periodeID == 0 ? val.periode === periode : val.periode == periodeID)
                    // // console.log(this.props.location.state.rawData)
                    // console.log(this.state.lastPeriod)
                    console.log(data)
                    console.log(periodeData)
                    console.log(defaultProps)
                    console.log(index)
                    this.setState({ listPeriode: defaultProps, periode: index === -1 ? periodeData[0] : periodeData[index] }, () => {
                        this.getMonth()
                    })
                }
            }
        })
    }

    getMonth() {
        api.create().getMonthTransaction().then(response => {
            let dateNow = new Date
            let month = format(dateNow, 'MMMM')
            console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    console.log(response);
                    let data = response.data.data
                    let monthID = this.state.rawData != null ? this.state.rawData.month : 0
                    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,
                    };
                    let index = data.findIndex((val) => monthID == 0 ? val.month_name == month : val.id == monthID)
                    console.log(index);
                    let selectedMonth = []
                    monthData.map((item, indexs) => {
                        if (indexs <= index) {
                            selectedMonth.push(item.month_value)
                        }
                    })

                    this.setState({ listMonth: defaultProps, month: index == -1 ? monthData[0] : monthData[index], selectedMonth }, () => {
                        this.getDasboardCAT()
                    })
                } 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' })
            }
        })
    }

    getDasboardCAT() {
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "months": this.state.month.month_id
        }
        let dataDashboard = []
        api.create().getDashboardCAT(payload).then((res) => {
            if (res.data.status == 'success') {
                console.log(res)
                // let resp = res.data.data
                this.setState({ dataDashboard: res.data.data }, () => {
                    setTimeout(() => {
                        this.setState({ loading: false })
                    }, 400);
                })
            }
            // else {
            //     this.setState({loading: false})
            // }
            // conole.log(JSON.stringify(payload))
        })
    }

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

    selectTab = (event, newEvent) => {
        this.setState({ tab: newEvent })
    }

    setSelectedKPI(data) {
        this.setState({ selectedKPI: data }, () => {
            let dataStorageCAT = localStorage.getItem(Constant.DATACAT)
            let userID = localStorage.getItem(Constant.USER)
            if (dataStorageCAT != 'datacat' && dataStorageCAT != null) {
                let arrayStorage = JSON.parse(dataStorageCAT)
                if (arrayStorage.length > 0) {
                    let indexID = arrayStorage.findIndex((val) => val.userID == userID)
                    if (indexID == -1) {
                        let listKPI = []
                        listKPI.push({
                            list: this.state.selectedKPI,
                            companyId: this.state.company.company_id
                        })
                        let payloadData = {
                            userID,
                            listKPI
                        }
                        arrayStorage.push(payloadData)
                        console.log('1')
                        console.log(arrayStorage)
                    } else {
                        let listKPI = arrayStorage[indexID].listKPI
                        let indexComp = listKPI.findIndex((val) => val.companyId == this.state.company.company_id)
                        if (indexComp == -1) {
                            listKPI.push({
                                list: this.state.selectedKPI,
                                companyId: this.state.company.company_id
                            })
                            // arrayStorage.push(payloadData)
                            arrayStorage[indexID].listKPI = listKPI
                            console.log('2')
                            console.log(arrayStorage)
                        } else {
                            arrayStorage[indexID].listKPI[indexComp].list = this.state.selectedKPI
                            console.log('3')
                            console.log(arrayStorage)
                        }


                    }
                    localStorage.setItem(Constant.DATACAT, JSON.stringify(arrayStorage))
                    console.log(localStorage.getItem(Constant.DATACAT))
                }
            } else {
                let arrayStorage = []
                let listKPI = []
                listKPI.push({
                    list: this.state.selectedKPI,
                    companyId: this.state.company.company_id
                })
                let payloadData = {
                    userID: localStorage.getItem(Constant.USER),
                    listKPI
                }
                arrayStorage.push(payloadData)
                localStorage.setItem(Constant.DATACAT, JSON.stringify(arrayStorage))
                console.log('4')
                console.log(arrayStorage)
            }
        })
    }

    render() {
        const perusahaan = [
            { value: 'TAP Group', label: 'TAP Group' },
            { value: '2019', label: '2019' },
            { value: '2018', label: '2018' },
            { value: '2017', label: '2017' },
            { value: '2016', label: '2016' },
        ]
        const periode = [
            { value: '2020', label: '2020' },
            { value: '2019', label: '2019' },
            { value: '2018', label: '2018' },
            { value: '2017', label: '2017' },
            { value: '2016', label: '2016' },
        ]

        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 className='a-s-p-mid no-header'>
                <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                    <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                        {this.state.messageAlert}
                    </Alert>
                </Snackbar>
                {this.state.loading && loadingComponent}
                <div className={"main-color"} style={{ padding: 27 }}>
                    <Typography style={{ fontSize: '16px', color: 'white' }}>Dashboard CAT Report</Typography>
                </div>
                <div style={{ padding: 20 }}>
                    <div style={{ marginTop: 0, display: 'flex' }}>
                        <Autocomplete
                            {...this.state.listCompany}
                            id="month"
                            onChange={(event, newInputValue) => this.setState({ company: newInputValue, loading: true }, () => {
                                let dataStorageCAT = localStorage.getItem(Constant.DATACAT)
                                let userID = localStorage.getItem(Constant.USER)
                                if (dataStorageCAT != 'datacat' && dataStorageCAT != null) {
                                    let arrayStorage = JSON.parse(dataStorageCAT)
                                    let indexListKPI = arrayStorage.findIndex((val) => val.userID == userID)
                                    let selectedKPI = []
                                    let indexListKPIDetail = -1
                                    if (indexListKPI != -1) {
                                        indexListKPIDetail = arrayStorage[indexListKPI].listKPI.findIndex((val) => val.companyId == this.state.company.company_id)
                                        if (indexListKPIDetail != -1) {
                                            selectedKPI = arrayStorage[indexListKPI].listKPI[indexListKPIDetail].list
                                        }
                                    }
                                    this.setState({ selectedKPI })
                                }
                                this.getDasboardCAT()
                            })}
                            disableClearable
                            style={{ maxWidth: 250, marginRight: 20 }}
                            renderInput={(params) => <TextField {...params} label="Company" margin="normal" style={{ marginTop: 7 }} />}
                            value={this.state.company}
                        />
                        <Autocomplete
                            {...this.state.listPeriode}
                            id="month"
                            onChange={(event, newInputValue) => this.setState({ periode: newInputValue, loading: true }, () => {
                                this.getDasboardCAT()
                            })}
                            disableClearable
                            style={{ maxWidth: 250, marginRight: 20 }}
                            renderInput={(params) => <TextField {...params} label="Periode" margin="normal" style={{ marginTop: 7 }} />}
                            value={this.state.periode}
                        />
                        <Autocomplete
                            {...this.state.listMonth}
                            id="month"
                            onChange={(event, newInputValue) => this.setState({ month: newInputValue, loading: true }, () => {
                                let index = this.state.listMonth.options.findIndex((val) => val.month_id == this.state.month.month_id)
                                let selectedMonth = []
                                this.state.listMonth.options.map((item, indexs) => {
                                    if (indexs <= index) {
                                        selectedMonth.push(item.month_value)
                                    }
                                })
                                this.setState({ selectedMonth })
                                this.getDasboardCAT()
                            })}
                            disableClearable
                            style={{ maxWidth: 250, marginRight: 20 }}
                            renderInput={(params) => <TextField {...params} label="Month" margin="normal" style={{ marginTop: 7 }} />}
                            value={this.state.month}
                        />
                    </div>
                    {/* <div style={{ marginTop: 20 }}>
                        <Autocomplete
                            {...this.state.listPeriode}
                            id="month"
                            onChange={(event, newInputValue) => this.setState({ periode: newInputValue, loading: true }, () => {
                                this.getDasboardCAT()
                            })}
                            disableClearable
                            style={{ maxWidth: 250, marginRight: 20 }}
                            renderInput={(params) => <TextField {...params} label="Periode" margin="normal" style={{ marginTop: 7 }} />}
                            value={this.state.periode}
                        />
                    </div> */}
                    {/* <div style={{ marginTop: 20 }}>
                        <Autocomplete
                            {...this.state.listMonth}
                            id="month"
                            onChange={(event, newInputValue) => this.setState({ month: newInputValue, loading: true }, () => {
                                let index = this.state.listMonth.options.findIndex((val) => val.month_id == this.state.month.month_id)
                                let selectedMonth = []
                                this.state.listMonth.options.map((item, indexs) => {
                                    if (indexs <= index) {
                                        selectedMonth.push(item.month_value)
                                    }
                                })
                                this.setState({ selectedMonth })
                                this.getDasboardCAT()
                            })}
                            disableClearable
                            style={{ maxWidth: 250, marginRight: 20 }}
                            renderInput={(params) => <TextField {...params} label="Month" margin="normal" style={{ marginTop: 7 }} />}
                            value={this.state.month}
                        />
                    </div> */}
                </div>

                {!this.state.loading && <div className="padding-20px" style={{ display: 'flex' }}>
                    <Paper style={{ marginTop: 10, minWidth: this.props.open ? this.props.width - 360 : this.props.width - 100 }}>
                        <AppBar position="static" style={{ borderTopRightRadius: 10, borderTopLeftRadius: 10 }}>
                            <Tabs indicatorColor="primary" value={this.state.tab} onChange={this.selectTab} aria-label="simple tabs example" style={{ backgroundColor: '#354960', borderColor: 'transparent', borderTopRightRadius: 10, borderTopLeftRadius: 10 }}>
                                <Tab label="Executive Scoreboard" style={{ color: '#fff', fontSize: 11 }} />
                                <Tab label="Strategy Map" style={{ color: '#fff', fontSize: 11 }} />
                                <Tab label="KPIs" style={{ color: '#fff', fontSize: 11 }} />
                            </Tabs>
                        </AppBar>
                        {this.state.tab === 0 ?
                            <ExceutiveScoreboard selectedKPI={this.state.selectedKPI} selectedMonth={this.state.selectedMonth} setSelectedKPI={this.setSelectedKPI.bind(this)} height={this.props.height} data={this.state.dataDashboard} dataPayload={{ month: this.state.month, periode: this.state.periode, company: this.state.company }} />
                            :
                            this.state.tab === 1 ?
                                <StrategiMap height={this.props.height} data={this.state.dataDashboard} dataPayload={{ month: this.state.month, periode: this.state.periode, company: this.state.company }} />
                                :
                                <KPIs height={this.props.height} selectedMonth={this.state.selectedMonth} width={this.props.open ? this.props.width - 360 : this.props.width - 100} data={this.state.dataDashboard} dataPayload={{ month: this.state.month, periode: this.state.periode, company: this.state.company }} />
                        }
                    </Paper>
                </div>}
            </div>
        )
    }
}