import { $userInfo, $userStatus } from "@/store/player"
import { useStore } from '@nanostores/react'
import { useEffect, useMemo, useState } from "react"
import {
    Table,
    TableBody,
    TableCell,
    TableFooter,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table"
import { socket } from "./socket"
import { ClientMessage } from "@/lib/types/message"
import { getUserPlayTime } from "@/lib/utils"

export const UserList = ({ roomName, serverTimeAdjust }: { roomName: string, serverTimeAdjust: number }) => {
    const userStatus = useStore($userStatus)
    const [_, setTick] = useState(0)
    
    useEffect(() => {
        const interval = setInterval(() => {
            setTick(t => t + 1)
        }, 500)
        return () => clearInterval(interval)
    }, [])

    const sortedUserStatus = useMemo(() => {
        return [...userStatus].sort((a, b) => {
            // 按照username排序
            return (a.username || '').localeCompare(b.username || '')
        })
    }, [userStatus])

    return (
        <Table key={userStatus.length}>
            <TableHeader>
                <TableRow>
                    <TableHead className="w-[72px]">用户名</TableHead>
                    <TableHead className="text-center">时间</TableHead>
                    <TableHead className="text-center">状态</TableHead>
                </TableRow>
            </TableHeader>
            <TableBody>
                {sortedUserStatus.map((user) => (
                    <TableRow key={user.userID}>
                        <TableCell className="font-medium">{user.username}</TableCell>
                        <TableCell className="text-center">{getUserPlayTime(user, serverTimeAdjust)}</TableCell>
                        <TableCell className="text-center">{user.playing == true ? '播放中' : '暂停中'}</TableCell>
                    </TableRow>
                ))}
                {userStatus.length == 0 && <><TableRow>
                    <TableCell className="text-center h-full align-middle" colSpan={3}>该房间暂无用户</TableCell>
                </TableRow></>}
            </TableBody>
            <TableFooter>
            </TableFooter>
        </Table>
    )
}