import { Paper, makeStyles, Grid, Typography } from "@material-ui/core";
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { IJobDataPaperProps } from "./JobDataPaper.types";
import Chart from 'chart.js'
import { Job } from "../../../Api/Job/Job";
import { IJobCountPerDate, IJobStatistics } from "../../../../../Application/DTOs/JobsDto/JobsDto.types";
import { format } from "date-fns";
import { useSelector } from "react-redux";
import { AppState } from "../../../Redux";
import { USER_ROLES } from "../../../Types/Constants";

const {
    COMPANY
} = USER_ROLES

const useStyles = makeStyles(() => ({
    centerText: {
        textAlign: 'center'
    },
    bottomRow: {
        color: 'white',
        backgroundColor: (props: IJobDataPaperProps) => props.color,
        padding: '10px 0'
    },
    title: {
        marginLeft: '10px'
    }
}))

const jobApi = new Job()

function JobDataPaper(props: IJobDataPaperProps) {
    const { title, color, status } = props
    const user = useSelector((state: AppState) => state.user)
    const classes = useStyles(props)
    const [t] = useTranslation('JobDataPaper')
    const canvasRef = useRef(null)
    const [jobStats, setJobStats] = useState<IJobStatistics | null>(null)
    const isUserCompany: boolean = user.response?.type === COMPANY
    const currentCompanyId = user.response?.company?.id

    const getJobsStatistics = useCallback(
        (status: string) => {
            jobApi.getJobsStatistics({
                status,
                companyId: isUserCompany ? String(currentCompanyId) : undefined
            })
                .then(response => {
                    const jobStats: IJobStatistics = response.data
                    setJobStats(jobStats)
                })
                .catch(err => {
                    console.log('err', err)
                })
        },
        [currentCompanyId, isUserCompany],
    )

    useEffect(() => {
        getJobsStatistics(status)

    }, [getJobsStatistics, status])

    useEffect(() => {
        let chart: Chart | undefined
        const labels: string[] = []
        const data: number[] = []

        if (canvasRef.current && !chart) {
            chart = new Chart(canvasRef.current || '', {
                type: 'line',
                data: {
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true,
                                stepSize: 1
                            }
                        }]
                    },
                    legend: {
                        display: false
                    },

                    tooltips: {

                        callbacks: {
                            label: () => '',
                            title: () => ''
                        }
                    }
                }
            })
        }

        if(chart && jobStats) {
            for (let i = 0; i < jobStats.perDate.length; i++) {
                const jobCount: IJobCountPerDate = jobStats.perDate[i];

                labels.push(format(new Date(jobCount.date), 'd'))
                data.push(jobCount.count)
            }


            chart.data = {
                labels,
                datasets: [{
                    label: t('no_of_jobs'),
                    data,
                    borderWidth: 1
                }]
            }

            chart.update()
        }


        return () => {
            chart?.destroy()
        }
    }, [jobStats, t])

    return (
        <Paper elevation={5}>
            <Grid
                container
                direction="column"
                spacing={2}
            >
                <Grid className={classes.title} item md={12}>
                    <Typography variant="h3" component="h2">
                        {jobStats?.total ?? 0}
                    </Typography>
                    <Typography color="textSecondary">
                        {title}
                    </Typography>
                </Grid>
                <Grid item md={12}>
                    {/* CHART */}
                    <canvas ref={canvasRef} />
                </Grid>
                <Grid item md={12}>
                    <Grid
                        container
                        direction="row"
                        justifyContent="center"
                        alignItems="center"
                        className={classes.bottomRow}
                    >
                        <Grid className={classes.centerText} item md={4}>
                            <Typography variant="h5" component="h2">
                                {jobStats?.perDay ?? 0}
                            </Typography>
                            <Typography>
                                {t('day')}
                            </Typography>
                        </Grid>
                        <Grid className={classes.centerText} item md={4}>
                            <Typography variant="h5" component="h2">
                                {jobStats?.perWeek ?? 0}
                            </Typography>
                            <Typography>
                                {t('week')}
                            </Typography>
                        </Grid>
                        <Grid className={classes.centerText} item md={4}>
                            <Typography variant="h5" component="h2">
                                {jobStats?.perMonth ?? 0}
                            </Typography>
                            <Typography>
                                {t('month')}
                            </Typography>
                        </Grid>

                    </Grid>
                </Grid>

            </Grid>
        </Paper>
    )
}

export default JobDataPaper