'use client'
import { useState } from "react"
import { ItemTableList } from "../components/ItemTableList"
import useAsyncEffect from "use-async-effect"
import { Mutex } from "async-mutex"
import { useItemStore } from "../providers/ItemsProvider"
import { useCurrentAuthenticatedUserStore } from "../providers"
import { useShallow } from "zustand/shallow"


const itemPageApiMutex = new Mutex()
const Items = () => {

    const [itemName, setItemName] = useState("")
    const [itemPrice, setItemPrice] = useState(0)
    const [inSeason, setInSeason] = useState(false)
    const [shouldSubmitDetails, setShouldSubmitDetails] = useState(false)

    const itemStore = useItemStore((state) => state)

    const authUserStore = useCurrentAuthenticatedUserStore(useShallow((state) => state))

    useAsyncEffect(async () => {
        if(shouldSubmitDetails && authUserStore.Admin)
        {
            setShouldSubmitDetails(false)
            const release = await itemPageApiMutex.acquire()
            await itemStore.createItem(itemName, inSeason, itemPrice)

            await release()
        }
    }, [shouldSubmitDetails])

    useAsyncEffect(async () => {
        if(authUserStore.Id === -1) {
            const release = await itemPageApiMutex.acquire()
            await authUserStore.sync()
            await release()
        }
    }, [authUserStore])


    return (
        <>
            <ItemTableList />
            {authUserStore.Admin && 
                <>
                    <h1 className="text-xl font-bold">Create Item</h1>
                    <input placeholder="item name" onChange={(e) => {
                        setItemName(e.currentTarget.value)
                    }}/>
                    <input placeholder="item price" onChange={(e) => {
                        const int_value = parseInt(e.currentTarget.value)
                        if(!Number.isNaN(int_value))
                            setItemPrice(int_value)
                    }}/>
                    In Season
                    <input className="ml-3" type="checkbox" onChange={(e) => {
                        setInSeason(e.target.checked)
                    }} />
                    <br />
                    <button onClick={() => {
                        setShouldSubmitDetails(true)
                    }} className="border p-1 mt-3 hover:bg-white hover:text-black">Create Item</button>
                </>
            }
        </>
        
    )
}

export default Items