import Typography from "@mui/material/Typography";
import * as React from "react";
import {useEffect, useMemo} from "react";
import {api} from "../../../lib/clients/api";
import {requests} from "../../../requests";
import {useAlert} from "../../../hooks/useAlert";
import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import {CocktailItemCalc} from "./CocktailItemCalc";
import {IngredientCalcCard} from "./IngredientCalcCard";

export function CalcPage() {
    const {createError} = useAlert();
    const [cocktails, setCocktails] = React.useState([]);
    const [load, setLoad] = React.useState(false);
    const [cocktailMap, setCocktailMap] = React.useState([]);

    const changeHandler = (id, value) => {
        setCocktailMap((prev) => ({
            ...prev,
            [id]: value
        }));
    }

    useEffect(() => {
        if (load) {
            return;
        }
        api().get(requests.cocktails.calc)
            .then((r) => {
                const data = r.data;
                if (data.length === 0) {
                    setLoad(false);
                    return;
                }
                setCocktails(data);
                let map = [];
                data.map((d) => {
                    map[d.id] = 1
                })
                setCocktailMap(map);
                setLoad(true);
            })
            .catch((r) => {
                setLoad(true);
                createError("Ошибка загрузки данных от сервера Status:" + r.code)
            })
        // eslint-disable-next-line
    }, [load]);

    const ingredients = useMemo(() => {
            let map = {}
            if (!cocktails) {
                return [];
            }
            cocktails.forEach((c) => {
                const receipts = c.receipt;
                const countMeter = cocktailMap[c.id];

                if (!receipts) {
                    return
                }
                receipts.forEach((r) => {
                    const ingredient = r.ingredient;
                    const id = ingredient.id;
                    const ingredientCount = r.count;

                    const resultCount = ingredientCount * countMeter;

                    if (map[id]) {
                        map[id] = {
                            ...map[id],
                            count: map[id].count + resultCount
                        }
                    } else {
                        map[id] = {
                            ingredient: ingredient,
                            count: resultCount
                        }
                    }
                })
            })
            return Object.values(map);
        },
        [cocktails, cocktailMap])

    const deleteHandler = (id) => {
        const state = cocktails.filter((c) => c.id !== id);
        setCocktails(state);
    }

    return (
        <Box padding={2}>
            <Typography variant="h4" align="center">Коктейли</Typography>
            <Stack mt={2}>
                {cocktails.map((item, i) => (
                    <CocktailItemCalc key={i} cocktail={item} deleteHandler={deleteHandler}
                                      changeHandler={changeHandler}/>
                ))}
            </Stack>

            <Typography variant="h4" mt={2} align="center">Ингредиенты</Typography>
            <Stack mt={2}>
                {ingredients.map((item, i) => (
                    <IngredientCalcCard key={i} count={item.count} ingredient={item.ingredient}/>
                ))}
            </Stack>
        </Box>
    )
}