import React, { useMemo } from 'react';
import { Plug } from 'lucide-react-native';

import type { SuperagentToolRendererProps } from '../../types';
import { ToolWidgetRow } from '../primitives/ToolWidgetRow';
import { getConnectionDisplayName, getFailureReason, isDeclinedResolution } from '../skillsAndConnectionsUtils';
import { getSettledWidgetStatus, parseToolArgs } from '../toolWidgetUtils';

/**
 * Settled states for the connection-style approval tools —
 * request_oauth_authorization and suggest_payments_installation. Mirrors the web
 * Request3rdPartyConnection header ("Connected to X" / "Connect to X" +
 * cancelled). The waiting-state connect flow stays with the timeline's
 * ToolApprovalCard.
 */
export function ConnectionStatusWidget({ isLastAssistantMessage, toolCall }: SuperagentToolRendererProps) {
  const args = useMemo(() => parseToolArgs(toolCall), [toolCall]);
  // Settled status keeps stale rows on old turns from spinning forever.
  const status = getSettledWidgetStatus(toolCall, isLastAssistantMessage);
  const name = getConnectionDisplayName(toolCall.name, args);

  // error means the request actually failed (oauth.py prechecks — flag-hidden
  // integration, disabled shared creds, invalid BYO connector — or an approved
  // connect that failed) — never a cancellation (stopped).
  const title =
    status === 'running'
      ? 'Connecting to'
      : status === 'success'
        ? 'Connected to'
        : status === 'error'
          ? 'Failed to connect to'
          : 'Connect to';
  const cancelled = isDeclinedResolution(status, toolCall);

  return (
    <ToolWidgetRow
      chipText={name}
      failureText={getFailureReason(status, toolCall)}
      icon={Plug}
      note={cancelled ? 'cancelled' : null}
      status={status}
      title={title}
    />
  );
}
