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

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

/**
 * set_secrets — settled states of the web SetSecrets card (the secure entry
 * form for the waiting state stays with ToolApprovalCard). Renders secret
 * NAMES and descriptions from the args schema only — the entered values live
 * in toolCall.user_input and must never be read or rendered here.
 */
export function SetSecretsWidget({ 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 schema = useMemo(() => getSecretSchemaItems(args), [args]);
  const [expanded, setExpanded] = useState(false);

  // error means the submitted secrets failed to save — never a skip (stopped).
  const title =
    status === 'running'
      ? 'Setting a secret'
      : status === 'success'
        ? 'Set a secret'
        : status === 'error'
          ? 'Failed to set secrets'
          : 'Set secrets';
  const skipped = isDeclinedResolution(status, toolCall);
  const note = skipped
    ? 'skipped'
    : schema.length > 0
      ? `${schema.length} ${schema.length === 1 ? 'field' : 'fields'}`
      : null;
  const canExpand = schema.length > 0 && status !== 'running';

  return (
    <ToolWidgetRow
      expanded={expanded}
      failureText={getFailureReason(status, toolCall)}
      icon={KeyRound}
      note={note}
      onToggle={canExpand ? () => setExpanded((current) => !current) : undefined}
      status={status}
      title={title}
    >
      <KeyValueList
        items={schema.map((secret) => ({
          label: secret.name,
          value: secret.description || 'secret value',
        }))}
      />
    </ToolWidgetRow>
  );
}
