"use client";

import { useFormStatus } from "react-dom";

function Arrow({ up }: { up: boolean }) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      className={`h-3.5 w-3.5 ${up ? "" : "rotate-180"}`}
    >
      <path d="M12 19V5" />
      <path d="m5 12 7-7 7 7" />
    </svg>
  );
}

function Submit({
  up,
  disabled,
  label,
}: {
  up: boolean;
  disabled?: boolean;
  label: string;
}) {
  const { pending } = useFormStatus();
  return (
    <button
      type="submit"
      disabled={pending || disabled}
      aria-label={label}
      title={label}
      className="flex h-8 w-8 items-center justify-center rounded-full border border-linen bg-white text-ink-soft transition-colors hover:border-teal hover:text-teal disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:border-linen disabled:hover:text-ink-soft"
    >
      <Arrow up={up} />
    </button>
  );
}

/** Up/down buttons that persist a one-slot reorder via a server action. */
export function MoveButtons({
  action,
  id,
  position,
  count,
}: {
  action: (formData: FormData) => void | Promise<void>;
  id: string;
  /** Zero-based index of this row. */
  position: number;
  /** Total number of rows, to disable at the ends. */
  count: number;
}) {
  if (count <= 1) return null;
  const atStart = position <= 0;
  const atEnd = position >= count - 1;
  return (
    <div className="flex flex-col gap-1.5">
      <form action={action}>
        <input type="hidden" name="id" value={id} />
        <input type="hidden" name="delta" value="-1" />
        <Submit up disabled={atStart} label="Move up" />
      </form>
      <form action={action}>
        <input type="hidden" name="id" value={id} />
        <input type="hidden" name="delta" value="1" />
        <Submit up={false} disabled={atEnd} label="Move down" />
      </form>
    </div>
  );
}
