"use client";

import { useActionState, useState } from "react";
import { awardCellarChoice, revokeCellarChoice } from "@/lib/actions/admin";

export function CellarChoiceControl({
  labelId,
  isCellarChoice,
}: {
  labelId: string;
  isCellarChoice: boolean;
}) {
  const [awarding, setAwarding] = useState(false);
  const [state, formAction, isPending] = useActionState(
    awardCellarChoice,
    undefined,
  );

  if (isCellarChoice) {
    return (
      <button
        type="button"
        onClick={() => {
          if (confirm("Revoke this label's Cellar Choice award?")) {
            revokeCellarChoice(labelId);
          }
        }}
        className="rounded-full border border-gold px-4 py-1.5 text-sm font-medium text-gold hover:bg-gold/10"
      >
        Revoke Cellar Choice
      </button>
    );
  }

  if (!awarding) {
    return (
      <button
        type="button"
        onClick={() => setAwarding(true)}
        className="rounded-full border border-charcoal/20 px-4 py-1.5 text-sm font-medium text-charcoal hover:bg-charcoal/5"
      >
        Award Cellar Choice
      </button>
    );
  }

  return (
    <form
      action={async (formData) => {
        await formAction(formData);
        setAwarding(false);
      }}
      className="flex flex-col gap-2"
    >
      <input type="hidden" name="labelId" value={labelId} />
      <input
        type="text"
        name="note"
        placeholder="Note (optional)"
        className="rounded border border-charcoal/20 bg-warm-white px-3 py-1.5 text-sm text-charcoal"
      />
      <div className="flex gap-2">
        <button
          type="submit"
          disabled={isPending}
          className="rounded-full bg-gold px-4 py-1.5 text-sm font-medium text-white hover:bg-gold/90 disabled:opacity-60"
        >
          {isPending ? "Awarding..." : "Award"}
        </button>
        <button
          type="button"
          onClick={() => setAwarding(false)}
          className="text-sm text-charcoal/60 hover:underline"
        >
          Cancel
        </button>
      </div>
      {state?.error && <p className="text-xs text-terracotta">{state.error}</p>}
    </form>
  );
}
