import {useEffect, useState} from "react";
import {Order} from "../../types/order";
import ordersApi from "../../api/ordersApi";
import {RootState} from "../../redux/store";
import {useDispatch, useSelector} from "react-redux";
import {setPage} from "../../features/ordersFilter/ordersFilterSlice";
import {parseOrderBy} from "../BarcodeScreen/useBarcodeOrders";


const useOrders = () => {
    const dispatch = useDispatch();
    const [orders, setOrders] = useState<Order[]>([]);
    const [isInitialized, setIsInitialized] = useState(false);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const filterState = useSelector((state: RootState) => state.ordersFilter);
    const filter2state = useSelector((state: RootState) => state.filter.state);
    const fetchOrders = async (): Promise<Order[]> => {
        return ordersApi.getOrders({
            ...parseOrderBy(filter2state.sorting),
            page: filterState.page,
            shipmentDate: "",
            shipmentWarehouseId: filter2state.shippingWarehouseId,
            status: -1

        });
    }

    const appendOrders = (newOrders: Order[]) => {
        setOrders([...newOrders, ...orders]);
    }
    const refresh = () => {
        setOrders([]);
        dispatch(setPage(0));
        fetchOrders().then(setOrders);
    }
    useEffect(() => {
        if (!isInitialized || filterState.isVisible) return;
        fetchOrders().then(appendOrders);
    }, [filterState.page]);


    useEffect(() => {
        if (!isInitialized || filterState.isVisible) return;
        fetchOrders().then(setOrders)
    }, [filterState.orderBy,
        filterState.desc,
        filterState.status,
        filterState.shipmentDate,
        filterState.isVisible,
        filterState.shippingWarehouse,
        filter2state
    ]);

    useEffect(() => {
        fetchOrders().then(newOrders => {
            setOrders(newOrders);
            setIsInitialized(true);

        })
    }, []);
    return {refresh, isRefreshing, orders};
}

export default useOrders;