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

import type { SuperagentToolRendererProps } from '../../types';
import { countArrayResults, getEntityName, getReadEntitiesFilterItems } from '../entityWidgetUtils';
import { KeyValueList } from '../primitives/KeyValueList';
import { ToolWidgetRow } from '../primitives/ToolWidgetRow';
import { getWidgetStatus, parseToolArgs } from '../toolWidgetUtils';

// read_entities — native port of the web ReadEntities row.
export function ReadEntitiesWidget({ toolCall }: SuperagentToolRendererProps) {
  const args = useMemo(() => parseToolArgs(toolCall), [toolCall]);
  const status = getWidgetStatus(toolCall.status);
  const [expanded, setExpanded] = useState(false);

  const filterItems = getReadEntitiesFilterItems(args);
  const resultCount = status === 'success' ? countArrayResults(toolCall.results) : null;

  return (
    <ToolWidgetRow
      chipText={getEntityName(args)}
      expanded={expanded}
      icon={Database}
      note={resultCount != null ? `${resultCount} ${resultCount === 1 ? 'record' : 'records'}` : null}
      onToggle={filterItems.length > 0 ? () => setExpanded((current) => !current) : undefined}
      status={status}
      title={status === 'running' ? 'Reading' : 'Read'}
    >
      <KeyValueList items={filterItems} />
    </ToolWidgetRow>
  );
}
