"use client";

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

export function RequestMeta({
  blendId,
  initialCount,
  labelCount,
  initialAlreadyRequested,
  isLoggedIn,
}: {
  blendId: string;
  initialCount: number;
  labelCount: number;
  initialAlreadyRequested: boolean;
  isLoggedIn: boolean;
}) {
  const [count, setCount] = useState(initialCount);
  const [alreadyRequested, setAlreadyRequested] = useState(initialAlreadyRequested);
  const [, startTransition] = useTransition();

  return (
    <p className="mt-1 flex items-center gap-2 text-sm text-charcoal/50">
      <span>
        {count} request{count === 1 ? "" : "s"}
        {labelCount > 0 &&
          ` · ${labelCount} label${labelCount === 1 ? "" : "s"} already`}
      </span>
      {isLoggedIn &&
        (alreadyRequested ? (
          <span className="text-xs text-charcoal/40">Requested</span>
        ) : (
          <button
            type="button"
            onClick={() => {
              setCount((c) => c + 1);
              setAlreadyRequested(true);
              startTransition(() => {
                requestLabel(blendId);
              });
            }}
            title="Add your own request for this blend"
            className="rounded-full border border-charcoal/20 px-2 py-0.5 text-xs font-medium text-charcoal hover:bg-charcoal/5"
          >
            +1
          </button>
        ))}
    </p>
  );
}
