'use client'
import { IconButton } from '@/components/ui/button'
import { useGetAIUserBaseInfo } from '@/hooks/aiUser'
import { useDoAiUserLiked } from '@/hooks/useCommon'
import { aiUserKeys, imKeys } from '@/lib/query-keys'
import { useQueryClient } from '@tanstack/react-query'
import { useParams, useRouter } from 'next/navigation'
import { useToken } from '@/hooks/auth'

const UserLikeButton = () => {
  const { userId } = useParams()
  const router = useRouter()
  const { isLogin } = useToken()
  const { data } = useGetAIUserBaseInfo({ aiId: Number(userId) })
  const { mutateAsync: doAiUserLiked } = useDoAiUserLiked()
  const { liked } = data || {}
  const queryClient = useQueryClient()

  const handleLike = () => {
    // 检查是否登录，如果未登录则跳转到登录页面
    if (!isLogin) {
      const currentPath = `/@${userId}`
      router.push(`/login?redirect=${encodeURIComponent(currentPath)}`)
      return
    }

    doAiUserLiked({ aiId: Number(userId), likedStatus: liked ? 'CANCELED' : 'LIKED' })
    queryClient.setQueryData(aiUserKeys.baseInfo({ aiId: Number(userId) }), (oldData: any) => {
      return {
        ...oldData,
        liked: !liked,
      }
    })
    queryClient.setQueryData(imKeys.imUserInfo(Number(userId)), (oldData: any) => {
      return {
        ...oldData,
        liked: !liked,
      }
    })
    queryClient.setQueryData(aiUserKeys.stat({ aiId: Number(userId) }), (oldData: any) => {
      return {
        ...oldData,
        likedNum: !liked ? oldData.likedNum + 1 : oldData.likedNum - 1,
      }
    })
  }

  return (
    <IconButton variant="tertiary" size="large" onClick={handleLike}>
      {!liked ? (
        <i className="iconfont icon-Like" />
      ) : (
        <i className="iconfont icon-Like-fill text-important-normal" />
      )}
    </IconButton>
  )
}

export default UserLikeButton
