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

export type Props = {
    productId: number;
}
const useBarcodeOrders = (props: Props) => {
    const [orders, setOrders] = useState<Order[]>([]);
    const [isUpdating, setIsUpdating] = useState(false);
    const {productId} = props;
    const {
        orderBy,
        isVisible,
        desc,
        shipmentDate,
        status,
        shippingWarehouse,
        city
    } = useSelector((state: RootState) => state.ordersFilter);
    const fetchOrders = async (): Promise<Order[]> => {
        return ordersApi.getOrdersByProduct({productId, orderBy, shipmentDate, status, shippingWarehouse,city, desc});
    }
    useEffect(() => {
        if (isVisible || productId < 0) return;
        setOrders([]);
        setIsUpdating(true);
        fetchOrders().then((fetchedOrders) => {
            setOrders(fetchedOrders);
            setIsUpdating(false);
        });
    }, [
        productId,
        isVisible,
        desc,
        orderBy,
        shipmentDate,
        status,
        shippingWarehouse]);

    return {orders, isUpdating}
}

export default useBarcodeOrders;