import Box from "@mui/material/Box";
import {useEffect, useMemo, useState} from "react";
import {api} from "../../lib/clients/api";
import {requests} from "../../requests";
import {useAlert} from "../../hooks/useAlert";
import {BarItem} from "./BarItem";
import {Loading} from "../core/Loading";
import * as React from "react";
import {useUser} from "../../hooks/useUser";

export function BarList({all}) {
    const {getError, createError} = useAlert();
    const {refresh} = useUser();
    const [bars, setBars] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        setLoading(true);
        api().get(`${requests.bar.list}?my=${!all}`)
            .then((r) => {
                setBars(r.data)
                setLoading(false);
            })
            .catch(() => getError())
        // eslint-disable-next-line
    }, []);
    const enterExist = useMemo(() => bars.find((b) => b.enter), [bars])
    const changeHandler = (row, value) => {
        let request;
        let newState;
        if (!all) {
            if (value && enterExist) {
                //todo: добавить переключение
                createError("Нельзя войти более чем в один бар одновременно")
                return;
            }
            request = api().patch(`${requests.bar.enter}${row.id}&value=${value}`);
            newState = bars.map((b) => {
                if (b.id !== row.id) {
                    return b;
                }
                return {
                    ...b,
                    enter: value
                }
            })
        } else {
            request = api().post(requests.bar.addToMyList, row);
            newState = bars.filter((b) => b.id !== row.id);
        }
        request.then(() => {
            setBars(newState)
            refresh();
        }).catch(() => getError())
    }
    return (
        <Box mt={2}>
            {
                bars.map((row) => {
                    return (
                        <BarItem key={row.id} row={row} changeHandler={changeHandler}
                        all={all} enterExist={enterExist}/>
                    )
                })
            }
            {/*Загрузчик*/}
            <Loading loading={loading}/>
        </Box>
    )
}