import * as React from 'react';
import Paper from '@material-ui/core/Paper';
import { ResponsiveBar } from '@nivo/bar'
import { Snackbar, TextField, Typography, withStyles } from '@material-ui/core';
import MuiAlert from '@material-ui/lab/Alert';
import { Autocomplete } from '@material-ui/lab';
import { titleCase } from '../../library/Utils';
import api from '../../api';
import Constant from '../../library/Constant';

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

// make sure parent container have a defined height when using
// responsive component, otherwise height will be 0 and
// no chart will be rendered.
// website examples showcase many properties,
// you'll often use just a few of them.
// const MyResponsiveBar = ({ data /* see data tab */ }) => (
    
// )

export default class DashboardFinancial extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [
        {
          "country": "AD",
          "hot dog": 6,
          "hot dogColor": "hsl(228, 70%, 50%)",
          "burger": 53,
          "burgerColor": "hsl(29, 70%, 50%)",
          "sandwich": 74,
          "sandwichColor": "hsl(148, 70%, 50%)",
          "kebab": 132,
          "kebabColor": "hsl(54, 70%, 50%)",
          "fries": 46,
          "friesColor": "hsl(2, 70%, 50%)",
          "donut": 146,
          "donutColor": "hsl(60, 70%, 50%)"
        },
        {
          "country": "AE",
          "hot dog": 167,
          "hot dogColor": "hsl(340, 70%, 50%)",
          "burger": 133,
          "burgerColor": "hsl(160, 70%, 50%)",
          "sandwich": 46,
          "sandwichColor": "hsl(330, 70%, 50%)",
          "kebab": 68,
          "kebabColor": "hsl(298, 70%, 50%)",
          "fries": 11,
          "friesColor": "hsl(89, 70%, 50%)",
          "donut": 119,
          "donutColor": "hsl(40, 70%, 50%)"
        },
        {
          "country": "AF",
          "hot dog": 60,
          "hot dogColor": "hsl(188, 70%, 50%)",
          "burger": 120,
          "burgerColor": "hsl(252, 70%, 50%)",
          "sandwich": 138,
          "sandwichColor": "hsl(152, 70%, 50%)",
          "kebab": 45,
          "kebabColor": "hsl(256, 70%, 50%)",
          "fries": 132,
          "friesColor": "hsl(201, 70%, 50%)",
          "donut": 130,
          "donutColor": "hsl(191, 70%, 50%)"
        },
        {
          "country": "AG",
          "hot dog": 84,
          "hot dogColor": "hsl(356, 70%, 50%)",
          "burger": 102,
          "burgerColor": "hsl(161, 70%, 50%)",
          "sandwich": 157,
          "sandwichColor": "hsl(177, 70%, 50%)",
          "kebab": 65,
          "kebabColor": "hsl(74, 70%, 50%)",
          "fries": 105,
          "friesColor": "hsl(82, 70%, 50%)",
          "donut": 90,
          "donutColor": "hsl(138, 70%, 50%)"
        },
        {
          "country": "AI",
          "hot dog": 144,
          "hot dogColor": "hsl(102, 70%, 50%)",
          "burger": 62,
          "burgerColor": "hsl(308, 70%, 50%)",
          "sandwich": 59,
          "sandwichColor": "hsl(101, 70%, 50%)",
          "kebab": 117,
          "kebabColor": "hsl(152, 70%, 50%)",
          "fries": 57,
          "friesColor": "hsl(297, 70%, 50%)",
          "donut": 34,
          "donutColor": "hsl(319, 70%, 50%)"
        },
        {
          "country": "AL",
          "hot dog": 84,
          "hot dogColor": "hsl(288, 70%, 50%)",
          "burger": 93,
          "burgerColor": "hsl(288, 70%, 50%)",
          "sandwich": 23,
          "sandwichColor": "hsl(64, 70%, 50%)",
          "kebab": 128,
          "kebabColor": "hsl(118, 70%, 50%)",
          "fries": 199,
          "friesColor": "hsl(125, 70%, 50%)",
          "donut": 184,
          "donutColor": "hsl(334, 70%, 50%)"
        },
        {
          "country": "AM",
          "hot dog": 44,
          "hot dogColor": "hsl(239, 70%, 50%)",
          "burger": 17,
          "burgerColor": "hsl(306, 70%, 50%)",
          "sandwich": 58,
          "sandwichColor": "hsl(317, 70%, 50%)",
          "kebab": 51,
          "kebabColor": "hsl(148, 70%, 50%)",
          "fries": 151,
          "friesColor": "hsl(344, 70%, 50%)",
          "donut": 174,
          "donutColor": "hsl(190, 70%, 50%)"
        }
      ],
    };
  }

  componentDidMount() {
    console.log(this.props.height)
  }

  getDetailUser() {
    let userId = localStorage.getItem(Constant.USER)
    api.create().getDetailUser(userId).then((response) => {
        if (response.data) {
            if (response.ok) {
                if (response.data.status === 'success') {
                    this.setState({ userCompany: response.data.data.company }, () => {
                        this.getCompanyActive()
                    })
                }
            }
        }
    })
    }

    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 ? this.state.rawData.company_id : 0
                    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,
                        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]) }, () => {
                        this.getLastPeriod()
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        if (response.data.message.includes("Someone Logged In")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', listCompany: null, company: null })
            }
        })
    }

    getLastPeriod() {
        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 }, () => {
                    this.getPeriode()
                })
            }
        })
    }

    getPeriode() {
        api.create().getPeriodeTransaction().then(response => {
            let currentYear = new Date().getFullYear()
            // console.log(currentYear)
            if (response.data) {
                if (response.data.status === "success") {
                    let data = []
                    response.data.data.map((item) => {
                        if (this.state.isApprover) {
                            if (item >= 2000 && item <= (Number(currentYear) + 1)) {
                                data.push(item)
                            }
                        } else {
                            if ((item >= 2000) && (item == this.state.lastPeriod || item < this.state.lastPeriod)) {
                                data.push(item)
                            }
                        }
                    })
                    let periodeData = data.map((item) => {
                        return {
                            periode: item,
                        }
                    })
                    let defaultProps = {
                        options: periodeData,
                        getOptionLabel: (option) => option.periode,
                    };
                    let periode = (this.state.lastPeriod == "" ? String(Number(currentYear) + 1) : this.state.lastPeriod)
                    let index = data.sort((a, b) => a - b).findIndex((val) => val === periode)
                    // console.log(data)
                    // console.log(this.state.latestPeriode)
                    // console.log(periodeData)
                    // console.log(index)
                    this.setState({ listPeriode: defaultProps, periode: index === -1 ? periodeData[0] : periodeData[index] }, () => {
                        // this.getDataTable()
                        // this.getSubmission()
                        this.getReportType()
                        // if (this.state.isApprover === true) {
                        //     this.getCompanySubmitted()
                        // } else {
                        //     this.getRevision()
                        // }
                    })
                }
            }
        })
    }

    getReportType() {
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "report_type": "Master Budget",
        }
        api.create().getReportTypeBody(payload).then(response => {
            console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    if (this.state.report.value === 2) {
                        response.data.data.map((item, index) => {
                            if (item.report_name === 'Balance Sheet') {
                                this.setState({ revisionType: item.revision }, ()=> {
                                    this.getSubmission()
                                })
                            }
                        })
                    } else if (this.state.report.value === 1) {
                        response.data.data.map((item, index) => {
                            if (item.report_name === 'Profit Loss') {
                                this.setState({ revisionType: item.revision }, ()=> {
                                    this.getSubmission()
                                })
                            }
                        })
                    } else {
                        this.setState({ revisionType: 0 }, ()=> {
                            this.getSubmission()
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                        if (response.data.message.includes("Someone Logged In")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })   
            }
        })
    }
  render() {
    const { data: chartData } = this.state;

    return (
        <div style={{ flex: 1, backgroundColor: '#f8f8f8' }} ref={this.myRef}>
            <div>
                <div className={"main-color"} style={{ height: 78, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                    <Typography style={{ fontSize: '16px', color: 'white' }}>Dashboard Financial</Typography>
                </div>
                <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                    <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                        {this.state.messageAlert}
                    </Alert>
                </Snackbar>
                <div style={{ padding: 20, width: '100%' }}>
                    <Paper style={{ paddingTop: 10 , height: this.props.height}}>
                        <div style={{ borderBottom: 'solid 1px #c4c4c4' }} >
                            <Typography style={{ fontSize: '12px', color: '#4b4b4b', margin: 10 }}>FINANCIAL SUMMARY OF TRIPUTRA GROUP</Typography>
                        </div>
                        <div style={{ minWidth: 'max-content', padding: '20px 20px 0px 20px' }}>
                            <div style={{ marginTop: 15 }}>
                                <Autocomplete
                                    options={this.state.reportType}
                                    getOptionLabel={(option) => titleCase(option.label)}
                                    id="typereport"
                                    onChange={(event, newInputValue) => this.setState({ report: newInputValue, loading: true, previewTable: false }, () => {
                                        this.getReportType()
                                    })}
                                    disableClearable
                                    style={{ width: 250 }}
                                    renderInput={(params) => <TextField {...params} label="Report Type" margin="normal" style={{ marginTop: 7 }} />}
                                    value={this.state.report}
                                />
                            </div>
                            <div style={{ marginTop: 15 }}>
                                <Autocomplete
                                    {...this.state.listCompany}
                                    id="company"
                                    disabled={this.state.intent === 'Home' ? true : false}
                                    onChange={(event, newInputValue) => this.setState({ company: newInputValue, loading: true, previewTable: false }, () => {
                                        this.getReportType()
                                    })}
                                    disableClearable
                                    style={{ width: 250 }}
                                    renderInput={(params) => <TextField {...params} label="Company" margin="normal" style={{ marginTop: 7 }} />}
                                    value={this.state.company}
                                />
                            </div>
                            <div style={{ marginTop: 15 }}>
                                <Autocomplete
                                    {...this.state.listPeriode}
                                    id="periode"
                                    onChange={(event, newInputValue) => this.setState({ periode: newInputValue, loading: true, previewTable: false }, () => {
                                        this.getReportType()
                                    })}
                                    disabled={this.state.intent === 'Home' ? true : false}
                                    disableClearable
                                    style={{ width: 250 }}
                                    renderInput={(params) =>
                                        <TextField {...params} label="Period" margin="normal" style={{ marginTop: 7 }}
                                        />}
                                    value={this.state.periode}
                                />
                            </div>
                        </div>
                        <div style={{height: Number(0.3 * this.props.height)}}>
                            <ResponsiveBar
                                data={chartData}
                                keys={[ 'hot dog', 'burger', 'sandwich', 'kebab', 'fries', 'donut' ]}
                                indexBy="country"
                                margin={{ top: 50, right: 130, bottom: 50, left: 60 }}
                                padding={0.3}
                                groupMode="grouped"
                                valueScale={{ type: 'linear' }}
                                indexScale={{ type: 'band', round: true }}
                                colors={{ scheme: 'nivo' }}
                                defs={[
                                    {
                                        id: 'dots',
                                        type: 'patternDots',
                                        background: 'inherit',
                                        color: '#38bcb2',
                                        size: 4,
                                        padding: 1,
                                        stagger: true
                                    },
                                    {
                                        id: 'lines',
                                        type: 'patternLines',
                                        background: 'inherit',
                                        color: '#eed312',
                                        rotation: -45,
                                        lineWidth: 6,
                                        spacing: 10
                                    }
                                ]}
                                fill={[
                                    {
                                        match: {
                                            id: 'fries'
                                        },
                                        id: 'dots'
                                    },
                                    {
                                        match: {
                                            id: 'sandwich'
                                        },
                                        id: 'lines'
                                    }
                                ]}
                                borderColor={{ from: 'color', modifiers: [ [ 'darker', 1.6 ] ] }}
                                axisTop={null}
                                axisRight={null}
                                axisBottom={{
                                    tickSize: 5,
                                    tickPadding: 5,
                                    tickRotation: 0,
                                    legend: 'country',
                                    legendPosition: 'middle',
                                    legendOffset: 32
                                }}
                                axisLeft={{
                                    tickSize: 5,
                                    tickPadding: 5,
                                    tickRotation: 0,
                                    legend: 'food',
                                    legendPosition: 'middle',
                                    legendOffset: -40
                                }}
                                labelSkipWidth={12}
                                labelSkipHeight={12}
                                labelTextColor={{ from: 'color', modifiers: [ [ 'darker', 1.6 ] ] }}
                                legends={[
                                    {
                                        dataFrom: 'keys',
                                        anchor: 'bottom-right',
                                        direction: 'column',
                                        justify: false,
                                        translateX: 25,
                                        translateY: 0,
                                        itemsSpacing: 0,
                                        itemWidth: 20,
                                        itemHeight: 24,
                                        itemDirection: 'left-to-right',
                                        itemOpacity: 0.85,
                                        symbolSize: 17,
                                        effects: [
                                            {
                                                on: 'hover',
                                                style: {
                                                    itemOpacity: 1
                                                }
                                            }
                                        ]
                                    }
                                ]}
                                animate={true}
                                motionStiffness={90}
                                motionDamping={15}
                            />
                        </div>
                    </Paper>
                </div>
            </div>
        </div>
    );
  }
}