import {useEffect, useMemo, useState} from "react";
import {useAlert} from "../../../hooks/useAlert";
import * as React from "react";
import {api} from "../../../lib/clients/api";
import {requests} from "../../../requests";
import {createHeadCell} from "../../../components/orders/createHeadCelll";
import {Loading} from "../../../components/core/Loading";
import OrderModal from "../../../components/orders/OrderModal";
import EnhancedTable from "../../../components/orders/EnhancedTable";

export function QueueContent({my}) {
    const [load, setLoad] = useState(false);
    const [orders, setOrders] = useState([]);
    const {createSuccess, createError} = useAlert();
    const [openModal, setOpenModal] = React.useState(false);
    const [selected, setSelected] = useState(null);

    useEffect(() => {
        setLoad(false);
        const url = my ? requests.bar.myOrders : requests.bar.order;
        api().get(url)
            .then(r => {
                setOrders(r.data);
                setLoad(true);
            })
            .catch(() => {
                createError("Ошибка при получении заказов");
                setLoad(true)
            })
        // eslint-disable-next-line
    }, []);

    const sliced = useMemo(() => orders.sort((a, b) => b.id - a.id), [orders])

    const cells = [
        createHeadCell('id', true, true, 'Номер заказа', "20px"),
        createHeadCell('cocktail.name', true, false, 'Коктейль', "40px"),
        createHeadCell('visitor.name', true, false, 'Клиент', "40px"),
        createHeadCell('status', true, true, 'Статус', "30px"),
    ];

    const changeOrderHandle = (row, status) => {
        let url = requests.bar.order + "?id=" + row.id;
        let isCancel = status === "CANCEL";
        let request = isCancel ? api().delete(url) : api().put(url);
        request
            .then(() => {
                createSuccess(isCancel ? "Заказ отменен" : "Заказ готов");
                let newArr = orders.filter((order) => {
                    if (order.id !== row.id) {
                        row.status = isCancel ? "CANCEL" : "DONE";
                        return row;
                    }
                    return order;
                })
                setOrders(newArr);
                setSelected(null);
                setOpenModal(false);
            })
            .catch(() => createError("Ошибка изменения заказа"))
    }
    const handleSelect = (row) => {
        setSelected(row);
        setOpenModal(true);
    }
    const handleCloseModal = () => {
        setOpenModal(false);
        setSelected(null);
    };

    const filterValues = !my ? ["DONE", "CANCEL"] : [];

    return (
        <>
            <Loading loading={!load}/>
            <OrderModal row={selected} handleClose={handleCloseModal} open={openModal}
                        handleChange={changeOrderHandle} my={my}/>
            <EnhancedTable name={"Заказы"} rows={sliced} cells={cells} handleSelect={handleSelect} filterEqual={false}
                           filterField={["status"]} filterValue={filterValues}/>
        </>
    )
}