import {useEffect, useState} from "react";
import {Order} from "../../types/order";
import ordersApi from "../../api/ordersApi";
import {setOrder} from "../../features/assembly/assemblySlice";
import {RootState} from "../../redux/store";
import {useDispatch, useSelector} from "react-redux";
import {
    refreshPagination,
    setOrderBy,
    setPage,
    setShippingWarehouse
} from "../../features/ordersFilter/ordersFilterSlice";


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 fetchOrders = async (): Promise<Order[]> => {
        return ordersApi.getOrders(
            filterState.page,
            filterState.orderBy,
            filterState.desc,
            filterState.shipmentDate,
            filterState.status,
            filterState.shippingWarehouse.id
        );
    }

    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
    ]);

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

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

export default useOrders;