import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import AddIcon from "@mui/icons-material/Add";
import * as React from "react";
import {useEffect, useState} from "react";
import {useAlert} from "../../hooks/useAlert";
import {Card} from "@mui/material";
import {SelectEdit} from "./SelectEdit";
import TextField from "@mui/material/TextField";
import DeleteForeverIcon from '@mui/icons-material/DeleteForever';
import {ingredientClient} from "../../lib/clients/IngredientClient";

export function EditCocktailReceipt({receipt, handler}) {
    const {createError} = useAlert()
    const [ingredients, setIngredients] = useState([]);
    const [units, setUnits] = useState([])

    useEffect(() => {
        ingredientClient.findAll(setIngredients, createError)
        ingredientClient.findUnit(setUnits, createError)
        // eslint-disable-next-line
    }, []);

    const selectHandler = (name, value) => {
        const ing = ingredients.find((i) => i.name === value)
        const newState = receipt.map((r, i) => {
            if (i !== name) {
                return r;
            }
            return {
                id: r.id,
                ingredient: {
                    id: ing.id,
                    isHave: ing.have,
                    name: ing.name
                },
                measure: r.measure
            }
        })
        handler("receipt", newState);
        checkAllowed(newState);
    }
    const unitHandler = (name, value) => {
        const ing = units.find((i) => i.name === value)
        const newState = receipt.map((r, i) => {
            if (i !== name) {
                return r;
            }
            return {
                id: r.id,
                ingredient: r.ingredient,
                unit: ing,
                count: r.count,
                measure: r.measure
            }
        })
        handler("receipt", newState);
        checkAllowed(newState);
    }
    const removeHandler = (index) => {
        const arr = receipt.filter((r, i) => i !== index)
        handler("receipt", arr)
        checkAllowed(arr)
    }
    const addHandler = () => {
        const oldState = receipt;
        oldState.push({
            id: null,
            ingredient: {
                id: null,
                isHave: false,
                name: ""
            },
            measure: ""
        });
        handler("receipt", oldState);
        checkAllowed(oldState);
    }
    const checkAllowed = (state) => {
        handler("isAllowed", !state.map((r) => r.ingredient.isHave).includes(false))
    }
    const measureHandler = (index, value) => {
        const newState = receipt.map((r, i) => {
            if (index !== i) {
                return r
            }
            return {
                ...r,
                measure: value
            }
        })
        handler("receipt", newState)
    }
    const countHandler = (index, value) => {
        const newState = receipt.map((r, i) => {
            if (index !== i) {
                return r
            }
            return {
                ...r,
                count: value
            }
        })
        handler("receipt", newState)
    }

    return (
        <Box mb={2}>
            {/*Заголовок*/}
            <Stack direction='row' justifyContent={'space-between'} sx={{mr: 1}}>
                <Typography ml={1} mt={1}>Рецепт</Typography>
                <IconButton onClick={() => addHandler()}>
                    <AddIcon/>
                </IconButton>
            </Stack>
            {/*Рецепт*/}
            <Stack sx={{mr: 1}}>
                {receipt.map((r, i) => {
                    return (
                        <Card key={i} sx={{ml: 0, mb: 1}}>
                            <Stack>
                                <Stack direction='row'>
                                    <SelectEdit width={'calc(65% - 28px)'} array={ingredients} value={r.ingredient.name}
                                                handler={selectHandler} label={"Ингредиент"}
                                                margin={1} attributeName={i}
                                    />
                                    <TextField sx={{width: 'calc(35% - 28px)', mt: 1}}
                                               label={"Кол-во"}
                                               variant="outlined"
                                               disabled
                                               value={r.measure}
                                               onChange={(e) => measureHandler(i, e.target.value)}
                                    />
                                    <IconButton sx={{mt: 2}}
                                                onClick={() => removeHandler(i)}
                                    >
                                        <DeleteForeverIcon/>
                                    </IconButton>
                                </Stack>
                                <Stack direction='row' ml={1} mb={1}>
                                    <TextField sx={{width: 'calc(35% - 28px)', mt: 1}}
                                               label={"Кол-во"}
                                               variant="outlined"
                                               value={r.count}
                                               onChange={(e) => countHandler(i, e.target.value)}
                                    />
                                    <SelectEdit width={'calc(65% - 28px)'} array={units}
                                                value={!r.unit ? null : r.unit.name}
                                                handler={unitHandler} label={"Ед."}
                                                margin={1} attributeName={i}
                                    />
                                </Stack>
                            </Stack>
                        </Card>
                    )
                })}
            </Stack>
        </Box>
    )
}