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";

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});
    }
    const refresh = () => {
        setOrders([]);
        setIsUpdating(true);
        fetchOrders().then((fetchedOrders) => {
            setOrders(fetchedOrders);
            setIsUpdating(false);
        });
    }
    useEffect(() => {
        if (isVisible || productId < 0) return;
        refresh()
    }, [
        productId,
        isVisible,
        desc,
        orderBy,
        shipmentDate,
        status,
        shippingWarehouse,
    ]);

    return {
        orders,
        refresh,
        isUpdating
    }
}

export default useBarcodeOrders;