"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"
      disabled={pending}
      className="flex items-center gap-1 hover:text-foreground transition-colors disabled:opacity-60 disabled:pointer-events-none"
      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-red-500 text-red-500" : ""}`} />
      {likeCount}
    </button>
  )
}
