"use client";

import { useState, useTransition } from "react";
import { Play } from "lucide-react";
import { checkAllAction } from "@/app/(dashboard)/actions";
import { Button } from "@/components/ui/button";

export function CheckAllButton({ running, disabled }: { running: boolean; disabled?: boolean }) {
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function start() {
    startTransition(async () => {
      setError(null);
      const result = await checkAllAction();
      if (!result.ok) setError(result.error);
    });
  }

  return (
    <span className="relative inline-flex">
      <Button onClick={start} disabled={disabled || running || pending}>
        <Play className="size-4" aria-hidden />
        {running || pending ? "Checking…" : "Check All"}
      </Button>
      {error && (
        <span
          role="alert"
          className="absolute top-full right-0 z-10 mt-1 rounded-md border border-red-200 bg-red-50 px-2 py-1 text-xs whitespace-nowrap text-red-700"
        >
          {error}
        </span>
      )}
    </span>
  );
}
