'use client'
import {useProfileStore} from '@/components/stores/profile'
import {Button} from '@/components/ui/button'
import {Avatar, AvatarFallback, AvatarImage} from '@/components/ui/avatar'
import {LogOutIcon, UserIcon} from 'lucide-react'
import {usePathname, useRouter} from 'next/navigation'
import {logout} from '@/actions/auth'
import {HoverCard, HoverCardContent, HoverCardTrigger} from '@/components/ui/hover-card'
import {User} from '@/lib/models'

export default function UserCenter(props: {
  profile: User
}) {
  const router = useRouter()
  const pathname = usePathname()
  const refreshProfile = useProfileStore(store => store.refreshProfile)

  const isAdminPage = pathname.startsWith('/admin') // 判断是否在后台页面
  const displayedName = !isAdminPage
    ? props.profile.username || props.profile.phone.substring(0, 3) + '****' + props.profile.phone.substring(7) || '用户'
    : '进入控制台'

  const doLogout = async () => {
    const resp = await logout()
    if (resp.success) {
      refreshProfile()
      router.replace('/')
    }
  }

  const toAdminPage = () => {
    if (!isAdminPage) {
      router.push('/admin')
    }
  }

  return (
    <HoverCard openDelay={150} closeDelay={150}>
      <HoverCardTrigger>
        <Button
          theme="ghost"
          className="flex gap-2 items-center h-12"
          onClick={toAdminPage}
        >
          <Avatar>
            <AvatarImage src={props.profile.avatar} alt="avatar"/>
            <AvatarFallback className="bg-primary-muted"><UserIcon/></AvatarFallback>
          </Avatar>
          <span>{displayedName}</span>
        </Button>
      </HoverCardTrigger>
      <HoverCardContent className="w-36 p-1" align="end">
        <Button
          theme="ghost"
          color="fail"
          className="w-full justify-start text-sm h-9 px-3"
          onClick={doLogout}>
          <LogOutIcon/>
          退出登录
        </Button>
      </HoverCardContent>
    </HoverCard>
  )
}
