import React from 'react'
import type { ActionRef } from '../../lib/collector-types'

export interface ActionConfirmDialogProps {
  itemTitle: string
  action: ActionRef
  open: boolean
  busy: boolean
  onConfirm: () => void
  onCancel: () => void
  host?: string
  revision?: string | number
  reversible?: boolean
}

/** Confirm destructive gateway actions before POSTing to the collector. */
export function ActionConfirmDialog({
  itemTitle,
  action,
  open,
  busy,
  onConfirm,
  onCancel,
  host,
  revision,
  reversible = false,
}: ActionConfirmDialogProps) {
  if (!open) return null

  const revisionLabel = revision !== undefined ? String(revision) : undefined
  const irreversibleSuffix = reversible ? '' : ' This cannot be undone.'

  return (
    <div
      className="fixed inset-0 z-[70] flex items-center justify-center bg-black/60 p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby="action-confirm-title"
      data-action-confirm
      data-testid="action-confirm"
    >
      <div className="w-full max-w-md rounded-xl border border-border-strong bg-surface-raised p-4 shadow-xl">
        <h3 id="action-confirm-title" className="text-[14px] font-semibold text-fg">
          Confirm {action.label}
        </h3>
        <p className="mt-2 text-[12.5px] text-fg-muted">
          {host && revisionLabel ? (
            <>
              Run <span className="font-semibold text-fg">{action.label}</span> on{' '}
              <span className="font-semibold text-fg">{host}</span> at revision{' '}
              <span className="font-semibold text-fg">{revisionLabel}</span>?
              {irreversibleSuffix}
            </>
          ) : revisionLabel ? (
            <>
              Run <span className="font-semibold text-fg">{action.label}</span> at revision{' '}
              <span className="font-semibold text-fg">{revisionLabel}</span>?
              {irreversibleSuffix}
            </>
          ) : (
            <>
              Run <span className="font-semibold text-fg">{action.label}</span> on{' '}
              <span className="font-semibold text-fg">{itemTitle}</span>? This cannot be undone.
            </>
          )}
        </p>
        <div className="mt-4 flex justify-end gap-2">
          <button
            type="button"
            onClick={onCancel}
            disabled={busy}
            className="cursor-pointer rounded-[7px] border border-border-strong bg-surface px-[11px] py-1 text-[11.5px] text-fg"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={onConfirm}
            disabled={busy}
            data-action-confirm-submit
            className="cursor-pointer rounded-[7px] border border-[var(--mod-color-accent-tint)] bg-[var(--mod-color-accent-tint)] px-[11px] py-1 text-[11.5px] font-semibold text-accent-fg"
          >
            {busy ? 'Running…' : action.label}
          </button>
        </div>
      </div>
    </div>
  )
}
