"use client";

import { useState, useTransition } from "react";
import { RefreshCw } from "lucide-react";
import { checkNowAction } from "@/app/(dashboard)/apps/actions";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/cn";

type CheckNowButtonProps = {
  id: string;
  name: string;
  disabled?: boolean;
  size?: "sm" | "md";
  /** Where to render the failure message relative to the button. */
  errorAlign?: "left" | "right";
};

export function CheckNowButton({ id, name, disabled, size = "sm", errorAlign = "right" }: CheckNowButtonProps) {
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function check() {
    startTransition(async () => {
      setError(null);
      // The result itself arrives through revalidation: the row re-renders
      // with the new status, so only a failure to run needs local state.
      const result = await checkNowAction(id);
      if (!result.ok) setError(result.error);
    });
  }

  return (
    <span className="relative inline-flex">
      <Button
        variant="secondary"
        size={size}
        onClick={check}
        disabled={disabled || pending}
        aria-label={`Check ${name} now`}
        title={disabled ? "Monitoring is disabled" : undefined}
      >
        <RefreshCw className={cn(size === "sm" ? "size-3.5" : "size-4", pending && "animate-spin")} aria-hidden />
        {pending ? "Checking…" : "Check Now"}
      </Button>
      {error && (
        <span
          role="alert"
          className={cn(
            "absolute top-full z-10 mt-1 rounded-md border border-red-200 bg-red-50 px-2 py-1 text-xs whitespace-nowrap text-red-700",
            errorAlign === "right" ? "right-0" : "left-0",
          )}
        >
          {error}
        </span>
      )}
    </span>
  );
}
