"use client";

import { clsx } from "clsx";
import { useState, useTransition, type ComponentProps } from "react";

type Props = {
  /** Short label shown in the normal state. */
  label: string;
  /** Wording for the armed state, e.g. "Click again to delete". */
  confirmLabel?: string;
  /** Resets to unarmed state after this many ms. */
  timeoutMs?: number;
  tone?: "danger" | "warning" | "primary";
  className?: string;
} & Omit<ComponentProps<"button">, "children" | "onClick">;

/**
 * Two-click confirmation button. Safe for destructive actions without
 * adding a modal. Use inside a <form> with a server action as usual —
 * the second click submits.
 */
export function ConfirmButton({
  label,
  confirmLabel = "Click again to confirm",
  timeoutMs = 4000,
  tone = "danger",
  className,
  type = "submit",
  ...rest
}: Props) {
  const [armed, setArmed] = useState(false);
  const [isPending, startTransition] = useTransition();

  const toneClasses =
    tone === "danger"
      ? "bg-red-600 text-white hover:bg-red-700"
      : tone === "warning"
        ? "bg-amber-500 text-white hover:bg-amber-600"
        : "bg-[var(--color-blue)] text-white hover:bg-[var(--color-blue-deep)]";

  return (
    <button
      {...rest}
      type={type}
      disabled={rest.disabled || isPending}
      onClick={(e) => {
        if (!armed) {
          e.preventDefault();
          setArmed(true);
          startTransition(() => {
            setTimeout(() => setArmed(false), timeoutMs);
          });
        }
      }}
      className={clsx(
        "inline-flex items-center justify-center rounded-lg px-3 py-1.5 text-[13px] font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-60",
        armed ? toneClasses : "bg-white text-[var(--color-ink)] ring-1 ring-[var(--color-line)] hover:bg-[var(--color-line)]/40",
        className,
      )}
    >
      {armed ? confirmLabel : label}
    </button>
  );
}
