import Box from "@mui/material/Box";
import {useEffect, useState} from "react";
import {api} from "../../lib/clients/api";
import {requests} from "../../requests";
import {useAlert} from "../../hooks/useAlert";
import Typography from "@mui/material/Typography";
import {VisitorItem} from "../../components/visitor/VisitorItem";
import Toolbar from "@mui/material/Toolbar";
import * as React from "react";
import Button from "@mui/material/Button";
import {useUser} from "../../hooks/useUser";

export function VisitorPage() {
    const {session, checkSession} = useUser();
    const [visitors, setVisitors] = useState([])
    const [open, setOpen] = useState(false);
    const {createError} = useAlert();

    useEffect(() => {
        api().get(requests.visitors.all)
            .then((r) => {
                setVisitors(r.data)
            })
            .catch(() => createError("Ошибка получения данных"))
        // eslint-disable-next-line
    }, []);
    useEffect(() => {
        setOpen(session.isActive);
    }, [session, checkSession])

    const changeHandler = (visitor) => {
        const arr = visitors.map((v) => {
            if(v.id === visitor.id) {
                return {
                    ...visitor,
                    invited: !visitor.invited
                }
            }
            return v;
        })
        api().post(`${requests.visitors.invite}id=${visitor.id}&value=${!visitor.invited}`)
            .then(() => setVisitors(arr))
            .catch(() => createError("Ошибка запроса"))

    }
    const changeShift = () => {
        api().post(`${requests.bar.session.change}?value=${!open}`)
            .then(() => {
                checkSession?.();
                setOpen(!open)
            })
            .catch(() => createError("Ошибка закрытия сессии"))
    }

    return (
        <Box>
            {/*Заголовок*/}
            <Toolbar>
                <Typography variant="h6" component="div" sx={{flexGrow: 1}}>Посетители</Typography>
            </Toolbar>
            <Box ml={0} mb={2}>
                {visitors.map((v) => {
                    return (
                        <VisitorItem key={v.id} visitor={v} changeHandler={changeHandler} open={open}/>
                    )
                })}
            </Box>

            <Button
                variant='contained'
                color={open ? 'error' : 'success'}
                onClick={() => changeShift()}
            >{`${open ? "Закрыть " : "Открыть "}смену`}</Button>

        </Box>
    )
}