import React, { useMemo } from 'react';
import { ScrollText } 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 {
  countBackendFunctionLogEntries,
  formatUnknownValue,
  getStringArg,
  getWidgetStatus,
  parseToolArgs,
} from '../toolWidgetUtils';

/**
 * get_backend_function_logs — summary only ("Read logs" + function chip +
 * entry count; see backend_function_tools.py).
 *
 * Web-parity gotcha: the fetched payload is the function's console output;
 * the web never renders it in chat (it lives in an admin-only debug
 * affordance). Everyone sees what was fetched (function + entry count); the
 * raw log lines render only when the host opts in via the
 * `showDebugPayloads` prop.
 */
export function GetBackendFunctionLogsWidget({ showDebugPayloads, toolCall }: SuperagentToolRendererProps) {
  const args = useMemo(() => parseToolArgs(toolCall), [toolCall]);
  const status = getWidgetStatus(toolCall.status);
  const functionName = getStringArg(args, ['function_name']);
  const entryCount = useMemo(
    () => countBackendFunctionLogEntries(toolCall.results),
    [toolCall.results],
  );

  const showRawLogs = Boolean(showDebugPayloads) && toolCall.results != null;

  return (
    <ToolWidgetRow
      chipText={functionName || null}
      expanded={showRawLogs}
      icon={ScrollText}
      note={entryCount != null ? `${entryCount} ${entryCount === 1 ? 'entry' : 'entries'}` : null}
      status={status}
      title={status === 'running' ? 'Reading logs' : 'Read logs'}
    >
      {showRawLogs ? (
        <ExpandableSection collapsedTitle="Show raw logs (debug)" expandedTitle="Hide raw logs">
          <CodeBlock code={formatUnknownValue(toolCall.results)} />
        </ExpandableSection>
      ) : null}
    </ToolWidgetRow>
  );
}
