import Paper from "@mui/material/Paper";
import React, {useEffect, useState} from "react";
import {api} from "../../lib/clients/api";
import {requests} from "../../requests";
import {useAlert} from "../../hooks/useAlert";
import {Card} from "@mui/material";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import Box from "@mui/material/Box";
import DeleteIcon from '@mui/icons-material/Delete';
import ElectricalServicesIcon from '@mui/icons-material/ElectricalServices';
import {getComparator} from "../../components/core/getComparator";
import Toolbar from "@mui/material/Toolbar";
import AddCircleIcon from '@mui/icons-material/AddCircle';
import {BarCreateModal} from "../../components/BarCreateModal";
import PowerIcon from '@mui/icons-material/Power';

export function BarChangePage() {
    const [bars, setBars] = useState([])
    const [open, setOpen] = useState(false)
    const {createError, createSuccess, createWarning} = useAlert();

    useEffect(() => {
        api().get(requests.bar.all)
            .then((r) => {
                setBars(r.data.sort(getComparator("name")))
            })
            .catch(() => {
                createError("Ошибка получения списков")
            })
        // eslint-disable-next-line
    }, []);
    const changeHandler = (bar) => {
        createWarning("Дождитесь окончания операции")
        api().post(`${requests.bar.change}/${bar.id}`)
            .then(() => createSuccess("Список изменен"))
            .catch(() => createError("Ошибка изменения активного списка"))

        const newState = bars.map((b) => {
            if (b.active) {
                return {
                    ...b, active: false
                }
            }
            if (b.id === bar.id) {
                return {
                    ...b, active: true
                }
            }
            return b;
        })
        setBars(newState);
    }
    const deleteHandler = (bar) => {
        if (bar.active) {
            createError("Нельзя удалить активный бар!")
            return;
        }
        api().delete(requests.bar.crud + bar.id)
            .then(() => createSuccess("Список удален"))
            .catch(() => createError("Ошибка удаления. Обновите страницу"))

        setBars(bars.filter((b) => b.id !== bar.id));
    }
    const createHandler = (name) => {
        api().post(requests.bar.crud + name)
            .then((r) => {
                createSuccess("Cписок создан");
                let state = bars;
                state.push(r.data);
                setBars(state)
                setOpen(false)
            }).catch(() => createError("Ошибка создания списка"))
    }

    function closeHandler() {
        setOpen(false)
    }

    return (<>
            <BarCreateModal open={open} close={closeHandler} create={createHandler}/>
            <Paper sx={{p: 1}}>
                <Toolbar>
                    <Typography variant='h6'>Списки ингредиентов (бары)</Typography>
                    <IconButton edge="end" onClick={() => setOpen(true)}>
                        <AddCircleIcon/>
                    </IconButton>
                </Toolbar>
                {bars.map((b) => {
                    return <Card key={b.id} sx={{m: 2, p: 2}}>
                        <Stack direction='row' justifyContent={'space-between'}>
                            <Typography>{b.name}</Typography>
                            {b.active && <IconButton disabled>
                                <PowerIcon/>
                            </IconButton>}
                            {!b.active && <Box>
                                <IconButton onClick={() => deleteHandler(b)}>
                                    <DeleteIcon/>
                                </IconButton>
                                <IconButton onClick={() => changeHandler(b)}>
                                    <ElectricalServicesIcon/>
                                </IconButton>
                            </Box>}
                        </Stack>
                    </Card>
                })}
            </Paper>
        </>

    )
}