"use client";

import { useFormStatus } from "react-dom";
import { advanceOrderStatus } from "./actions";

/**
 * Nested inside the form so `useFormStatus` can see it — the hook reports only
 * on the form it renders within.
 *
 * The confirmation stays a native `confirm()` in the click handler, as before:
 * returning false there cancels the submit, so a seller who backs out never
 * reaches the Server Action.
 */
function SubmitButton({ next, label }: { next: string; label: string }) {
  const { pending } = useFormStatus();

  return (
    <button
      type="submit"
      onClick={(e) => {
        if (!confirm(`Mark order as "${label}"?`)) e.preventDefault();
      }}
      disabled={pending}
      className={`rounded-lg px-4 py-2 text-sm font-medium ${
        next === "cancelled"
          ? "bg-red-50 text-red-700 ring-1 ring-red-200 hover:bg-red-100"
          : "bg-[#CC1414] text-white hover:bg-[#a30f0f]"
      } disabled:opacity-60`}
    >
      {pending ? "…" : next === "cancelled" ? "Cancel order" : `Mark ${label.toLowerCase()}`}
    </button>
  );
}

/**
 * One form per available transition. The order id and target status ride along
 * as hidden inputs, so the browser posts everything the action needs without the
 * page having to hold the order in client state.
 */
export default function AdvanceStatusButton({ id, next, label }: { id: number; next: string; label: string }) {
  return (
    <form action={advanceOrderStatus}>
      <input type="hidden" name="id" value={id} />
      <input type="hidden" name="status" value={next} />
      <SubmitButton next={next} label={label} />
    </form>
  );
}
