import { Box, Typography, useTheme } from "@mui/material";
import { BarChart } from '@mui/x-charts/BarChart';
import { PieChart } from '@mui/x-charts/PieChart';
import { BarSeriesType } from '@mui/x-charts'
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { fetchStatisticsVolume, fetchStatisticsRevenue, fetchOrderStatus, fetchStockPercent } from "../query/Queries.tsx";
import { useAccount } from "../AccountProvider.tsx";
import { getColorFromPercent } from "../../util/ColorUtil.tsx";

export default function StatisticsInfo() {
    const theme = useTheme();
    const { t } = useTranslation();

    const [monthlyVolume, setMonthlyVolume] = useState<BarSeriesType[]>([]);
    const [monthlyVolumeXaxis, setMonthlyVolumeXaxis] = useState([{ data: [] }]);
    const [totalVolume, setTotalVolume] = useState([]);

    const [monthlyRevenue, setMonthlyRevenue] = useState<BarSeriesType[]>([]);
    const [monthlyRevenueXaxis, setMonthlyRevenueXaxis] = useState([{ data: [] }]);
    const [totalRevenue, setTotalRevenue] = useState([]);

    const [orderStatus, setOrderStatus] = useState([]);

    const [stockPercent, setStockPercent] = useState([]);
    

    const { user: loginData } = useAccount();


    const { data: dataVolume } = useQuery({
        queryKey: ["fetchStatisticsVolume", loginData],
        queryFn: () => fetchStatisticsVolume(loginData ? loginData : { email: "", password: "", session: "", customerId: -1, isAdmin: false }),
        retry: 0,
        retryDelay: 0,
    });

    const { data: dataRevenue } = useQuery({
        queryKey: ["fetchStatisticsRevenue", loginData],
        queryFn: () => fetchStatisticsRevenue(loginData ? loginData : { email: "", password: "", session: "", customerId: -1, isAdmin: false }),
        retry: 0,
        retryDelay: 0,
    });

    const { data: dataOrderStatus } = useQuery({
        queryKey: ["fetchOrderStatus", loginData],
        queryFn: () => fetchOrderStatus(loginData ? loginData : { email: "", password: "", session: "", customerId: -1, isAdmin: false }),
        retry: 0,
        retryDelay: 0,
    });

    const { data: dataStockPercent } = useQuery({
        queryKey: ["fetchStockPercent", loginData],
        queryFn: () => fetchStockPercent(loginData ? loginData : { email: "", password: "", session: "", customerId: -1, isAdmin: false }),
        retry: 0,
        retryDelay: 0,
    });
    

    useEffect(() => {
        if (dataVolume) {
            const cmm = []
            const cmmx = monthlyVolumeXaxis
            const tv = []
            let i = 0
            for (const cat in dataVolume.catMonthMap) {
                for (const timestamp in dataVolume.catMonthMap[cat]) {
                    const date = new Date(parseInt(timestamp))
                    const formattedDate = date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, '0')
                    if (!cmmx[0].data.includes(formattedDate)) {
                        cmmx[0].data.push(formattedDate);
                    }
                    const datapoint = dataVolume.catMonthMap[cat][timestamp]
                    if(cmm.length == i) {
                        cmm.push({ id: i, data: [], label: t(cat), type: "bar" })
                    }
                    cmm[i].data.push(datapoint)

                    if(tv.length == i) {
                        tv.push({ id: i, value: 0, label: t(cat)})
                    }
                    tv[i].value += datapoint
                }
                i++;
            }
            
            setMonthlyVolume(cmm)
            setMonthlyVolumeXaxis(cmmx)
            setTotalVolume(tv)
        }
    }, [dataVolume]);

    useEffect(() => {
        if (dataRevenue) {
            const cmm = []
            const cmmx = monthlyRevenueXaxis
            const tv = []
            let i = 0
            for (const cat in dataRevenue.catMonthMap) {
                for (const timestamp in dataRevenue.catMonthMap[cat]) {
                    const date = new Date(parseInt(timestamp))
                    const formattedDate = date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, '0')
                    if (!cmmx[0].data.includes(formattedDate)) {
                        cmmx[0].data.push(formattedDate);
                    }
                    const datapoint = dataRevenue.catMonthMap[cat][timestamp] / 100
                    if(cmm.length == i) {
                        cmm.push({ id: i, data: [], label: t(cat), type: "bar" })
                    }
                    cmm[i].data.push(datapoint)

                    if(tv.length == i) {
                        tv.push({ id: i, value: 0, label: t(cat)})
                    }
                    tv[i].value += datapoint
                }
                i++;
            }
            
            setMonthlyRevenue(cmm)
            setMonthlyRevenueXaxis(cmmx)
            setTotalRevenue(tv)
        }
    }, [dataRevenue]);

    useEffect(() => {
        if(dataOrderStatus) {
            const orderStatus = []
            for(var status in dataOrderStatus) {
                orderStatus.push({value: dataOrderStatus[status], label: t(status)})
            }
            setOrderStatus(orderStatus)
        }
    }, [dataOrderStatus]) ;

    useEffect(() => {
        if(dataStockPercent) {
            const stockPercent = []
            let i = 0
            for(let x = 0; x < 10; x++) {
                stockPercent.push({value: 0, label: String(x*10), color: getColorFromPercent(String(x*10))});
            }
            for(var cat in dataStockPercent) {
                for(var percent in dataStockPercent[cat]) {
                    let index = stockPercent.findIndex( (entry) => entry.label == percent)
                    const datapoint = dataStockPercent[cat][percent]
                    if(index === -1) {
                        index = stockPercent.push({value: 0, label: percent, color: getColorFromPercent(percent)}) -1
                    }
                    stockPercent[index].value += datapoint
                }
                i++
            }
            setStockPercent(stockPercent)
        }
    }, [dataStockPercent])

    return (
        <Box className="" sx={{ color: theme.palette.text.primary }}>
            <Typography mt={4} variant="h4" align="center" gutterBottom>
                {t("salesStatistics")}
            </Typography>

            <Box sx={{ mb: 4 }}>
                <Typography variant="h6" align="center" gutterBottom>
                    {t("monthlySalesVolume")}
                </Typography>
                <BarChart
                    series={monthlyVolume}
                    height={290}
                    xAxis={monthlyVolumeXaxis}
                />
            </Box>
            <Box sx={{ mb: 4 }}>
                <Typography variant="h6" align="center" gutterBottom>
                    {t("monthlySalesRevenue")}
                </Typography>
                <BarChart
                    series={monthlyRevenue}
                    height={290}
                    xAxis={monthlyRevenueXaxis}
                />
            </Box>
            <Box display={"flex"} mb={9}>
                <Box className="vw20" sx={{ m: 2 }}>
                    <Typography variant="h6" align="center" gutterBottom>
                        {t("itemVolumeDistribution")}
                    </Typography>
                    <PieChart
                        series={[{
                            data: totalVolume,
                            highlightScope: { fade: 'global', highlight: 'item' },
                            faded: { innerRadius: 30, additionalRadius: -30, color: 'gray' },
                        }]}
                        width={200}
                        height={200}
                    />
                </Box>

                <Box className="vw20" sx={{ m: 2 }}>
                    <Typography variant="h6" align="center" gutterBottom>
                        {t("itemRevenueDistribution")}
                    </Typography>
                    <PieChart
                        series={[{
                            data: totalRevenue,
                            highlightScope: { fade: 'global', highlight: 'item' },
                            valueFormatter: (v) => (v ? `${v.value}€` : '-'), 
                        }]}
                        width={200}
                        height={200}
                    />
                </Box>
                <Box className="vw20" sx={{ m: 2 }}>
                    <Typography variant="h6" align="center" gutterBottom>
                        {t("stockFulfillment")}
                    </Typography>
                    <PieChart
                        series={[{
                            data: stockPercent,
                            innerRadius: 10,
                            outerRadius: 85,
                            cornerRadius: 5,
                            paddingAngle: 2
                        }]}
                        width={200}
                        height={200}
                        hideLegend
                    />
                </Box>
                <Box className="vw20" sx={{ m: 2 }}>
                    <Typography variant="h6" align="center" gutterBottom>
                        {t("orderStatus")}
                    </Typography>
                    <PieChart
                        series={[{
                            data: orderStatus,
                            innerRadius: 20,
                            outerRadius: 70,
                            cornerRadius: 5,
                            paddingAngle: 1,
                            highlightScope: { fade: 'global', highlight: 'item' },
                            faded: { innerRadius: 30, additionalRadius: -10, color: 'gray' },
                        }]}
                        height={200}
                        width={200}
                    />
                </Box>
            </Box>
        </Box>
    );
}
