import { useState } from "react";
import { ChevronUp } from "lucide-react";

import { cn } from "@/lib/utils";

export interface UpvoteButtonProps {
  votes: number;
  /** Whether the current user has already voted. One vote per user. */
  voted?: boolean;
  /** Fired when the user toggles their vote. */
  onVote?: () => void;
}

/**
 * Compact vertical vote control: a chevron over a tabular-nums count. Toggles the
 * caller's vote on click and reflects the optimistic count. Used on upvote boards
 * (ideas, feature requests) as the left-hand action of a list row.
 */
export function UpvoteButton({
  votes,
  voted: initialVoted = false,
  onVote,
}: UpvoteButtonProps) {
  const [voted, setVoted] = useState(initialVoted);
  const count = votes + (voted ? 1 : 0);

  return (
    <button
      type="button"
      aria-pressed={voted}
      aria-label={voted ? "Remove your vote" : "Upvote this request"}
      onClick={() => {
        setVoted((v) => !v);
        onVote?.();
      }}
      className={cn(
        "flex w-14 shrink-0 flex-col items-center justify-center gap-1 border px-2 py-3 transition-colors",
        voted
          ? "border-primary bg-primary/5 text-foreground"
          : "border-border text-muted-foreground hover:border-foreground/30 hover:text-foreground",
      )}
    >
      <ChevronUp className="size-4" />
      <span className="text-body-small font-semibold tabular-nums">
        {count}
      </span>
    </button>
  );
}
