"use client";

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

type Badge = {
  id: string;
  threshold: number;
  name: string;
};

export function BadgeRow({ badge }: { badge: Badge }) {
  const [editing, setEditing] = useState(false);
  const [state, formAction] = useActionState(updateBadge, undefined);

  return (
    <li className="rounded-lg border border-charcoal/10 bg-warm-white p-4">
      {editing ? (
        <form
          action={async (formData) => {
            await formAction(formData);
            setEditing(false);
          }}
          className="flex flex-wrap items-center gap-2"
        >
          <input type="hidden" name="badgeId" value={badge.id} />
          <input
            type="number"
            name="threshold"
            min={1}
            defaultValue={badge.threshold}
            className="w-20 rounded border border-charcoal/20 bg-cream px-2 py-1 text-charcoal"
          />
          <input
            type="text"
            name="name"
            defaultValue={badge.name}
            className="flex-1 rounded border border-charcoal/20 bg-cream px-3 py-1 text-charcoal"
          />
          <button
            type="submit"
            className="text-sm font-medium text-terracotta hover:underline"
          >
            Save
          </button>
          <button
            type="button"
            onClick={() => setEditing(false)}
            className="text-sm text-charcoal/60 hover:underline"
          >
            Cancel
          </button>
        </form>
      ) : (
        <div className="flex items-center justify-between gap-4">
          <span className="text-charcoal">
            <strong>{badge.threshold}</strong> &middot; {badge.name}
          </span>
          <button
            type="button"
            onClick={() => setEditing(true)}
            className="text-sm text-terracotta hover:underline"
          >
            Edit
          </button>
        </div>
      )}
      {state?.error && <p className="mt-1 text-sm text-terracotta">{state.error}</p>}
    </li>
  );
}
