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

import type { SuperagentToolRendererProps } from '../../types';
import { CodeBlock } from '../primitives/CodeBlock';
import { ExpandableSection } from '../primitives/ExpandableSection';
import { ToolWidgetRow } from '../primitives/ToolWidgetRow';
import { toolWidgetStyles } from '../primitives/toolWidgetStyles';
import { formatUnknownValue, getStringArg, getWidgetStatus, parseToolArgs } from '../toolWidgetUtils';

/**
 * test_backend_function — native port of the web TestBackendFunction row
 * ("Testing/Tested <name>"; "Checking/Checked" when called without a
 * payload), extended with collapsed payload/response disclosures so the
 * invocation details stay inspectable on mobile.
 */
export function TestBackendFunctionWidget({ toolCall }: SuperagentToolRendererProps) {
  const args = useMemo(() => parseToolArgs(toolCall), [toolCall]);
  const status = getWidgetStatus(toolCall.status);
  const functionName = getStringArg(args, ['function_name']) || 'function';
  const payload = args?.payload ?? null;
  const hasPayload = payload != null;

  const title = status === 'running'
    ? (hasPayload ? 'Testing' : 'Checking')
    : (hasPayload ? 'Tested' : 'Checked');
  const response = status === 'running' ? null : toolCall.results ?? null;
  const hasDetails = hasPayload || response != null;

  return (
    <ToolWidgetRow
      chipText={functionName}
      expanded={hasDetails}
      icon={FlaskConical}
      status={status}
      title={title}
    >
      <View style={toolWidgetStyles.widgetBodyGap}>
        {hasPayload ? (
          <ExpandableSection collapsedTitle="Show payload" expandedTitle="Hide payload">
            <CodeBlock code={formatUnknownValue(payload)} />
          </ExpandableSection>
        ) : null}
        {response != null ? (
          <ExpandableSection collapsedTitle="Show response" expandedTitle="Hide response">
            <CodeBlock code={formatUnknownValue(response)} variant={status === 'error' ? 'error' : undefined} />
          </ExpandableSection>
        ) : null}
      </View>
    </ToolWidgetRow>
  );
}
