'use client'
import {useProfileStore} from '@/components/stores-provider'
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'

type UserCenterProps = {
  profile: User
}

export default function UserCenter(props: UserCenterProps) {
  const router = useRouter()

  // 登录控制
  const refreshProfile = useProfileStore(store => store.refreshProfile)
  const doLogout = async () => {
    const resp = await logout()
    if (resp.success) {
      refreshProfile().then()
      router.replace('/')
    }
  }

  // 展示与跳转
  const pathname = usePathname()
  const isAdminPage = pathname.startsWith('/admin') // 判断是否在后台页面
  const displayName = () => {
    if (props.profile.username) return props.profile.username // 优先显示用户名
    if (props.profile.phone) {
      const phone = props.profile.phone
      return `${phone.substring(0, 3)}****${phone.substring(7)}`
    }
    return null
  }

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

  return (
    <HoverCard openDelay={150} closeDelay={150}>
      <HoverCardTrigger>
        <Button
          theme="ghost"
          className="flex gap-2 items-center h-12"
          onClick={handleAvatarClick}
        >
          <Avatar>
            <AvatarImage src={props.profile.avatar} alt="avatar"/>
            <AvatarFallback className="bg-primary-muted"><UserIcon/></AvatarFallback>
          </Avatar>
          {/* 根据是否在后台页面显示不同内容 */}
          {isAdminPage ? (
            <span>{displayName() || '用户'}</span> // 后台显示姓名/脱敏手机号/默认"用户"
          ) : (
            <span>进入控制台</span> // 前台显示"进入控制台"
          )}
        </Button>
      </HoverCardTrigger>
      <HoverCardContent className="w-36 p-1" align="end">
        {/* <Button
          theme="ghost"
          className="w-full justify-start text-sm h-9 px-3"
          onClick={() => router.push('/admin/profile')}>
          <UserPenIcon/>
          个人中心
        </Button> */}
        <Button
          theme="ghost"
          color="fail"
          className="w-full justify-start text-sm h-9 px-3"
          onClick={doLogout}>
          <LogOutIcon/>
          退出登录
        </Button>
      </HoverCardContent>
    </HoverCard>
  )
}
