"use client";

import Link from "next/link";
import { useState, useTransition } from "react";
import type { VoteType } from "@prisma/client";
import { voteLabel } from "@/lib/actions/votes";

export function VoteButtons({
  labelId,
  thumbsUpCount,
  userVote,
  isLoggedIn,
}: {
  labelId: string;
  thumbsUpCount: number;
  userVote: VoteType | null;
  isLoggedIn: boolean;
}) {
  const [count, setCount] = useState(thumbsUpCount);
  const [vote, setVote] = useState(userVote);
  const [, startTransition] = useTransition();

  if (!isLoggedIn) {
    return (
      <Link
        href="/login"
        className="rounded-full border border-charcoal/20 px-4 py-2 text-sm font-medium text-charcoal hover:bg-charcoal/5"
      >
        Log in to vote
      </Link>
    );
  }

  function handleVote(type: VoteType) {
    const newVote = vote === type ? null : type;
    const deltaUp = (newVote === "up" ? 1 : 0) - (vote === "up" ? 1 : 0);
    setCount((c) => c + deltaUp);
    setVote(newVote);
    startTransition(() => {
      voteLabel(labelId, type);
    });
  }

  return (
    <div className="flex items-center gap-3">
      <button
        type="button"
        onClick={() => handleVote("up")}
        aria-pressed={vote === "up"}
        className={`flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium ${
          vote === "up"
            ? "border-terracotta bg-terracotta/10 text-terracotta"
            : "border-charcoal/20 text-charcoal hover:bg-charcoal/5"
        }`}
      >
        &#9650; {count}
      </button>
      <button
        type="button"
        onClick={() => handleVote("down")}
        aria-pressed={vote === "down"}
        title="Private, only used for moderation, never shown publicly"
        className={`rounded-full border px-4 py-2 text-sm font-medium ${
          vote === "down"
            ? "border-charcoal bg-charcoal/10 text-charcoal"
            : "border-charcoal/20 text-charcoal/60 hover:bg-charcoal/5"
        }`}
      >
        &#9660;
      </button>
    </div>
  );
}
