"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { ChevronUp, ChevronDown } from "lucide-react"
import { fetchApi } from "@/lib/api-client"
import { useAuth } from "@/components/auth-provider"
import { toast } from "sonner"

interface VoteButtonsProps {
  questionId: number
  initialUpvotes: number
}

export function VoteButtons({ questionId, initialUpvotes }: VoteButtonsProps) {
  const [upvotes, setUpvotes] = useState(initialUpvotes)
  const [isVoting, setIsVoting] = useState(false)
  const { user } = useAuth()

  const handleVote = async (voteType: 'up' | 'down') => {
    if (!user) {
      toast.error("Please log in to vote")
      return
    }

    setIsVoting(true)
    try {
      await fetchApi('forum.php', {
        method: 'PUT',
        body: JSON.stringify({
          question_id: questionId,
          vote_type: voteType
        })
      })
      
      setUpvotes(prev => voteType === 'up' ? prev + 1 : prev - 1)
      toast.success("Vote recorded")
    } catch (error: any) {
      toast.error(error.message || "Failed to record vote")
    } finally {
      setIsVoting(false)
    }
  }

  return (
    <div className="w-12 sm:w-16 bg-muted/20 flex flex-col items-center py-4 gap-1 border-r">
      <Button 
        variant="ghost" 
        size="icon" 
        className="h-8 w-8 hover:text-primary"
        onClick={() => handleVote('up')}
        disabled={isVoting}
      >
        <ChevronUp className="h-6 w-6" />
      </Button>
      <span className="font-bold text-sm">{upvotes}</span>
      <Button 
        variant="ghost" 
        size="icon" 
        className="h-8 w-8 hover:text-destructive"
        onClick={() => handleVote('down')}
        disabled={isVoting}
      >
        <ChevronDown className="h-6 w-6" />
      </Button>
    </div>
  )
}
