"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { ChevronUp, ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"

type VoteButtonProps = {
  initialCount: number
  orientation?: "vertical" | "horizontal"
}

export function VoteButton({ initialCount, orientation = "vertical" }: VoteButtonProps) {
  const [count, setCount] = useState(initialCount)
  const [userVote, setUserVote] = useState<-1 | 0 | 1>(0)

  function handleUpvote() {
    if (userVote === 1) {
      setUserVote(0)
      setCount(initialCount)
    } else {
      setUserVote(1)
      setCount(initialCount + 1)
    }
  }

  function handleDownvote() {
    if (userVote === -1) {
      setUserVote(0)
      setCount(initialCount)
    } else {
      setUserVote(-1)
      setCount(initialCount - 1)
    }
  }

  const isVertical = orientation === "vertical"

  return (
    <div className={cn(
      "flex items-center rounded-xl p-1",
      isVertical ? "flex-col bg-secondary/50" : "flex-row gap-1"
    )}>
      <Button
        variant="ghost"
        size="icon"
        className={cn(
          "h-8 w-8 rounded-lg transition-all",
          userVote === 1 
            ? "bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 shadow-sm shadow-emerald-500/20" 
            : "text-muted-foreground hover:text-emerald-400 hover:bg-emerald-500/10"
        )}
        onClick={handleUpvote}
      >
        <ChevronUp className={cn("h-5 w-5 transition-transform", userVote === 1 && "scale-110")} />
        <span className="sr-only">Upvote</span>
      </Button>
      <span
        className={cn(
          "min-w-[2rem] text-center font-bold tabular-nums transition-all",
          isVertical ? "py-1 text-base" : "px-1 text-sm",
          userVote === 1 && "text-emerald-400 scale-110",
          userVote === -1 && "text-destructive",
          userVote === 0 && "text-foreground"
        )}
      >
        {count}
      </span>
      <Button
        variant="ghost"
        size="icon"
        className={cn(
          "h-8 w-8 rounded-lg transition-all",
          userVote === -1 
            ? "bg-destructive/20 text-destructive hover:bg-destructive/30 shadow-sm shadow-destructive/20" 
            : "text-muted-foreground hover:text-destructive hover:bg-destructive/10"
        )}
        onClick={handleDownvote}
      >
        <ChevronDown className={cn("h-5 w-5 transition-transform", userVote === -1 && "scale-110")} />
        <span className="sr-only">Downvote</span>
      </Button>
    </div>
  )
}
