'for client'
import { Mutex } from "async-mutex"
import styled from "styled-components"
import useAsyncEffect from "use-async-effect"
import { useShallow } from "zustand/shallow"
import { useOrderStore } from "../providers/OrderProvider"
import { OrderTableRow } from "./OrderTableRow"

type OrderTableProps = {
    page: number,
    filter: number,
    orderer: string,
    dateDue: string,
    datePlaced: string
}

const OrderList = styled.ul`
`

const mutex = new Mutex()

export const OrderTableList = ({page, filter, orderer, dateDue, datePlaced}: OrderTableProps) => {
        const orderStore = useOrderStore(useShallow((state) => ({
            ...state
        })))

        useAsyncEffect(async () => {
            const release = await mutex.acquire()
            await orderStore.sync(page, filter, {
                orderer:  orderer,
                date_due: dateDue,
                date_placed: datePlaced
            })
            release()
        }, [page, filter, orderer, dateDue, datePlaced])

        return (
            <OrderList>
                {orderStore.orders.map((o) => (
                    <OrderTableRow key={o.Id} orderId={o.Id} orderer={o.Orderer} dateDue={o.DateDue} datePlaced={o.DatePlaced} amountPaid={o.AmountPaid} orderTotal={o.OrderTotal} amountDue={o.AmountDue} filled={o.Filled} delivered={o.Delivered} />
                ))}
            </OrderList>
        )
}