// Manual fleet-wide analysis trigger: button + confirm dialog. Analysis is
// read-only (heavy Prometheus reads, no cluster changes), so a lightweight
// confirm — not a preview workflow — is the right amount of friction.
// onTriggered lets call sites reload immediately; the pages' existing
// polling then surfaces progress. A 409 (run already in flight) renders
// inline in the dialog.

"use client";

import { useState } from "react";
import { triggerRun } from "@/lib/api-client";
import { Button, type ButtonSize, type ButtonVariant } from "@/components/ui/Button";
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";

export function RunTriggerButton({
  totalRegions,
  label,
  variant = "primary",
  size = "sm",
  onTriggered,
}: {
  /** Fleet size, for the dialog copy. */
  totalRegions: number;
  label: string;
  variant?: ButtonVariant;
  size?: ButtonSize;
  /** Fired after a successful trigger so the page can reload instantly. */
  onTriggered?: () => void;
}) {
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const confirm = async (): Promise<void> => {
    setBusy(true);
    try {
      await triggerRun();
      setError(null);
      setOpen(false);
      onTriggered?.();
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setBusy(false);
    }
  };

  const scopeText = totalRegions > 0 ? `all ${totalRegions} regions` : "the whole fleet";

  return (
    <>
      <Button
        variant={variant}
        size={size}
        onClick={() => {
          setError(null);
          setOpen(true);
        }}
      >
        {label}
      </Button>
      <ConfirmDialog
        open={open}
        title="Analyze"
        body={
          <>
            <p>
              This will analyze {scopeText} — reading metrics from Prometheus over the
              configured lookback. Read-only: no changes to any cluster.
            </p>
            {error ? <p className="mt-2 text-danger">{error}</p> : null}
          </>
        }
        confirmLabel="Start analysis"
        busy={busy}
        onConfirm={() => void confirm()}
        onCancel={() => {
          if (!busy) setOpen(false);
        }}
      />
    </>
  );
}
