"use client"

import { togglePostLike } from "@/lib/api/posts"
import { toApiError } from "@/lib/errors"
import { notifyInfo } from "@/lib/toast"
import { useRequireAuth } from "@/lib/use-require-auth"
import { Heart } from "lucide-react"
import { useState } from "react"

interface PostLikeButtonProps {
  postId: string
  initialLiked: boolean
  initialLikeCount: number
}

export function PostLikeButton({ postId, initialLiked, initialLikeCount }: PostLikeButtonProps) {
  const { requireAuth } = useRequireAuth()
  const [liked, setLiked] = useState(initialLiked)
  const [likeCount, setLikeCount] = useState(initialLikeCount)
  const [pending, setPending] = useState(false)

  return (
    <button
      type="button"
      aria-label={liked ? "取消点赞帖子" : "点赞帖子"}
      disabled={pending}
      className="flex items-center gap-1 text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-60"
      onClick={() =>
        requireAuth(() => {
          if (pending) return

          const prevLiked = liked
          const prevCount = likeCount
          const nextLiked = !prevLiked

          setLiked(nextLiked)
          setLikeCount(Math.max(0, prevCount + (nextLiked ? 1 : -1)))
          setPending(true)

          togglePostLike(postId, prevLiked)
            .catch((err: unknown) => {
              setLiked(prevLiked)
              setLikeCount(prevCount)
              if (err instanceof Error && err.message === "UNAUTHORIZED") {
                notifyInfo("请先登录")
                return
              }
              notifyInfo(toApiError(err).msg)
            })
            .finally(() => {
              setPending(false)
            })
        })
      }
    >
      <Heart className={`h-4 w-4 ${liked ? "fill-destructive text-destructive" : ""}`} />
      {likeCount}
    </button>
  )
}
