'use client'
import { useShallow } from "zustand/shallow"
import { useUserStore } from "../providers/UsersProvider"
import useAsyncEffect from "use-async-effect"
import styled from "styled-components"
import { useRef, useState } from "react"

type UserTableProps = {
    page: number
}
const UserTableStyle = styled.table`
    width: 100%
        `
const UserTableHead = styled.thead`
    background-color: #34067eff
`

const UserTH = styled.th`
    align: center
`
const UserTableItem = styled.td`
    align: center
`

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

const UserTableRow = styled.tr`

`

export const UserTable = ({page}: UserTableProps) => {
    
    const userStore = useUserStore(useShallow((state) => ({
        ...state
    })))
    console.log(page)

    const [callLock, setCallLock] = useState<boolean>(false)

    const callLockRef = useRef(callLock)
    useAsyncEffect(async () => {
        if(!callLockRef.current) {
            callLockRef.current = true
            setCallLock(true)
            await userStore.sync(page)
            callLockRef.current = false
            setCallLock(false)
        }
    }, [page])
    console.log(userStore.tableUsers)
    return (
    <UserTableStyle>
        <UserTableHead>
            <UserTH>id</UserTH>
            <UserTH>name</UserTH>
            <UserTH>position</UserTH>
            <UserTH>active</UserTH>
            <UserTH>admin</UserTH>
        </UserTableHead>
        <UserTableBody>
        {userStore.tableUsers.map((u) => (
            <UserTableRow key={u.Id}>
                <UserTableItem>{u.Id}</UserTableItem> 
                <UserTableItem>{u.Name}</UserTableItem> 
                <UserTableItem>{u.JobPosition}</UserTableItem> 
                <UserTableItem><input type="checkbox" defaultValue={u.Active ? "yes" : "no"} onChange={async (e) => {
                    if(u.Active)
                        await userStore.deactivateUser(u.Id)
                    else
                        await userStore.activateUser(u.Id)
                }}/></UserTableItem> 
                <UserTableItem><input type="checkbox" value={u.Admin ? "yes" : "no"} onChange={async (e) => {
                    if(u.Admin)
                        await userStore.demoteUser(u.Id)
                    else
                        await userStore.promoteUser(u.Id)
                }}/></UserTableItem> 
            </UserTableRow>))}
        </UserTableBody>
    </UserTableStyle>
    )
}