"use client";

import Link from "next/link";
import { useState, useTransition } from "react";
import { requestLabel } from "@/lib/actions/requests";

export function RequestLabelButton({
  blendId,
  requestCount,
  alreadyRequested,
  isLoggedIn,
}: {
  blendId: string;
  requestCount: number;
  alreadyRequested: boolean;
  isLoggedIn: boolean;
}) {
  const [requested, setRequested] = useState(alreadyRequested);
  const [count, setCount] = useState(requestCount);
  const [, startTransition] = useTransition();

  if (!isLoggedIn) {
    return (
      <Link
        href="/login"
        className="text-sm font-medium text-terracotta hover:underline"
      >
        Log in to request a label for this blend
      </Link>
    );
  }

  if (requested) {
    return (
      <p className="text-sm font-medium text-charcoal/60">
        You requested a label for this blend
        {count > 1 && ` (${count} total requests)`}.
      </p>
    );
  }

  return (
    <button
      type="button"
      onClick={() => {
        setRequested(true);
        setCount((c) => c + 1);
        startTransition(() => {
          requestLabel(blendId);
        });
      }}
      className="rounded-full bg-terracotta px-5 py-2 text-sm font-medium text-white hover:bg-terracotta/90"
    >
      Request a label
    </button>
  );
}
