import { Mutex } from "async-mutex"
import { useState } from "react"
import styled from "styled-components"
import useAsyncEffect from "use-async-effect"
import { GetItemHistory } from "../client/controllers"
import { ItemHistoryResponse } from "../client/response"

type ItemHistoryTableProps = {
    itemId: number
}

const ItemHistoryTableStyle = styled.table`
    width: 100%
        `
const ItemHistoryTableHead = styled.thead`
    background-color: #34067eff
`
const ItemHistoryTableItem = styled.td`
    align: center
`

const ItemHistoryTH = styled.th`
    align: center
`

const ItemHistoryTableBody = styled.tbody`
    > :nth-child(even) {
        background-color: #410041ff;
    }
    > :hover {
        background-color: #707070ff;
    }
`

const ItemHistoryTableRow = styled.tr`

`

const itemHistoryMutex = new Mutex()

export const ItemHistoryTable = ({itemId}: ItemHistoryTableProps) => {
    const [itemPriceHistory, setItemPriceHistory] = useState<ItemHistoryResponse[]>([])

    useAsyncEffect(async () => {
        if(itemPriceHistory.length === 0) {
            const release = await itemHistoryMutex.acquire()
            setItemPriceHistory(await GetItemHistory(itemId))
            await release()
        }
    }, [])

    console.log(itemPriceHistory)

    return (
        <ItemHistoryTableStyle>
            <ItemHistoryTableHead>
                <tr>
                    <ItemHistoryTH>
                        item
                    </ItemHistoryTH>
                    <ItemHistoryTH>
                        price
                    </ItemHistoryTH>
                    <ItemHistoryTH>
                        valid from
                    </ItemHistoryTH>
                    <ItemHistoryTH>
                        valid to
                    </ItemHistoryTH>
                </tr>
            </ItemHistoryTableHead>
            <ItemHistoryTableBody>
                {itemPriceHistory.map((iph) => (
                    <ItemHistoryTableRow key = {iph.ItemId + new Date(iph.ValidFrom).getMilliseconds()}>
                        <ItemHistoryTableItem>
                            {iph.ItemName}
                        </ItemHistoryTableItem>
                        <ItemHistoryTableItem>
                            {Math.trunc(parseInt(iph.ItemPrice) * 100) / 100}
                        </ItemHistoryTableItem>
                        <ItemHistoryTableItem>
                            {new Date(iph.ValidFrom).toLocaleDateString()}
                        </ItemHistoryTableItem>
                        <ItemHistoryTableItem>
                            {new Date(iph.ValidTo).toLocaleDateString()}
                        </ItemHistoryTableItem>
                    </ItemHistoryTableRow>
                ))}
            </ItemHistoryTableBody>
        </ItemHistoryTableStyle>
    )
}