import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import * as React from "react";
import {useEffect, useState} from "react";
import Paper from "@mui/material/Paper";
import {Autocomplete, FormControl, FormControlLabel, InputLabel} from "@mui/material";
import {api} from "../../../lib/clients/api";
import {requests} from "../../../requests";
import {useAlert} from "../../../hooks/useAlert";
import {useSearchParams} from "react-router-dom";
import TextField from "@mui/material/TextField";
import Switch from "@mui/material/Switch";
import Stack from "@mui/material/Stack";
import Button from "@mui/material/Button";
import Select from "@mui/material/Select";
import MenuItem from "@mui/material/MenuItem";
import {getComparator} from "../../../components/core/getComparator";

const emptyIngredient = {
    id: null,
    name: "",
    enName: "",
    have: false,
    image: null,
    type: "",
    alcohol: false,
    abv: null,
    description: null
}

export function EditIngredientPage() {
    const [searchParams] = useSearchParams();
    const [ingredients, setIngredients] = useState([]);
    const [types, setTypes] = useState([]);
    const [ingredient, setIngredient] = useState(emptyIngredient)
    const {createError, createSuccess} = useAlert();
    useEffect(() => {
        api().get(requests.bar.ingredientList)
            .then((r) => {
                const arr = r.data.sort(getComparator("asc", "name"));
                setIngredients(arr)

                const currentId = searchParams.get("id");
                if (!currentId) {
                    return;
                }
                const currentIngredient = arr.find((r) => r.id === (currentId * 1));
                if (!currentIngredient) {
                    return;
                }
                setIngredient(currentIngredient);
            })
            .catch(() => createError("Ошибка получения данных"))

        api().get(requests.bar.type)
            .then((r) => setTypes(r.data.sort(getComparator("asc", "name"))))
        // eslint-disable-next-line
    }, []);

    const changeIngredientValue = (name, value) => {
        setIngredient((prev) => ({
            ...prev,
            [name]: value
        }))
    }
    const saveIngredientHandler = () => {
        api().patch(requests.bar.ingredient, ingredient)
            .then(() => createSuccess("Ингредиент сохранен"))
            .catch(() => createError("Ошибка сохранения"))
    }

    return (
        <Box>
            {/*Заголовок*/}
            <Toolbar>
                <Typography variant="h6" component="div" sx={{flexGrow: 1}}>Ингредиенты</Typography>
            </Toolbar>
            {/*Поиск*/}
            <Paper elevation={6} sx={{my: 2, display: 'grid', p: 2}}>
                <Autocomplete
                    disablePortal
                    options={ingredients}

                    defaultChecked={emptyIngredient}
                    onChange={(e, v) => {
                        console.log(v);
                        return !v ? setIngredient(emptyIngredient) : setIngredient(v)
                    }}
                    isOptionEqualToValue={(selected, value) => selected.id === value.id}
                    getOptionKey={(selected) => selected.id}
                    getOptionLabel={(selected) => selected.name}
                    renderInput={(params) => <TextField {...params} label="Ингредиенты"/>}
                />
            </Paper>
            {/*Форма ингредиента*/}
            <Paper elevation={6} sx={{my: 2, display: 'grid', p: 1, pb: 2}}>
                <Stack>
                    <Box display={'flex'} justifyContent={'flex-end'} pr={2}>
                        <FormControlLabel control={
                            <Switch
                                checked={ingredient.have}
                                onChange={() => changeIngredientValue("have", !ingredient.have)}
                            />}
                                          label={"Наличие"} labelPlacement={'start'}/>
                    </Box>
                    <Box>
                        <img src={ingredient.image} alt={""} loading={'eager'}/>
                    </Box>
                    <Box m={1}>
                        <TextField sx={{mr: 1, mb: 2, minWidth: 330}}
                                   variant="outlined" label={"Название"}
                                   value={ingredient.name}
                                   onChange={(e) => changeIngredientValue("name", e.target.value)}/>
                        <TextField sx={{mr: 1, mb: 2, minWidth: 330}}
                                   label="Английское название" variant="outlined"
                                   value={ingredient.enName}
                                   onChange={(e) => changeIngredientValue("enName", e.target.value)}/>
                    </Box>

                    <Box height={70} mt={1} ml={1}>
                        <FormControlLabel sx={{pt: 1}}
                                          control={
                                              <Switch
                                                  checked={ingredient.alcohol}
                                                  onChange={() => changeIngredientValue("alcohol", !ingredient.alcohol)}
                                              />}
                                          label="Алкогольный"/>
                        {ingredient.alcohol && (
                            <TextField sx={{width: 100}}
                                       variant='outlined' label='Градус'
                                       value={!ingredient.abv ? "" : ingredient.abv}
                                       onChange={(e) => changeIngredientValue("abv", e.target.value)}/>
                        )}
                    </Box>

                    <Box mb={2} ml={1}>
                        <FormControl sx={{width: 330}}>
                            <InputLabel id="select-label">Категория</InputLabel>
                            <Select
                                id="select-label"
                                autoWidth
                                label={"Категория"}
                                value={!ingredient.type ? "" : ingredient.type}
                                onChange={(e) => changeIngredientValue("type", e.target.value)}
                            >
                                <MenuItem value="">
                                    <em>None</em>
                                </MenuItem>
                                {types.map((c) => {
                                    return (<MenuItem key={c.id} value={c.name}>{c.name}</MenuItem>)
                                })}
                            </Select>
                        </FormControl>
                    </Box>

                    <Box pr={2} ml={1}>
                        <TextField sx={{width: '100%'}}
                                   label={"Описание"} variant='outlined' multiline
                                   value={!ingredient.description ? "" : ingredient.description}/>
                    </Box>
                </Stack>
            </Paper>
            <Box display={'flex'} justifyContent={'flex-end'}>
                <Button variant='contained' onClick={() => saveIngredientHandler()}>Сохранить</Button>
            </Box>
        </Box>
    )
}