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

import type { SuperagentToolRendererProps } from '../../types';
import { DiffView } from '../primitives/DiffView';
import { ToolWidgetRow } from '../primitives/ToolWidgetRow';
import { getFailureReason, getIdentityTitle, identityDiffLines } from '../skillsAndConnectionsUtils';
import { getSettledWidgetStatus, getStringArg, parseToolArgs } from '../toolWidgetUtils';

/**
 * update_identity — native port of the web's inline identity-diff card
 * (FunctionDisplay.tsx). The web diffs against the previous file content from
 * earlier messages; that isn't available on-device, so the body shows the
 * written memory lines as additions (removed rows for memory.md deletes).
 */
export function UpdateIdentityWidget({ isLastAssistantMessage, toolCall }: SuperagentToolRendererProps) {
  const args = useMemo(() => parseToolArgs(toolCall), [toolCall]);
  // Settled status keeps stale rows on old turns from spinning forever;
  // stopped renders as an error row so it never reads as completed.
  const status = getSettledWidgetStatus(toolCall, isLastAssistantMessage);
  const fileName = getStringArg(args, ['name']);
  const diff = useMemo(() => identityDiffLines(args), [args]);
  const [expanded, setExpanded] = useState(false);

  const title = getIdentityTitle(status, fileName);
  const canExpand = diff.length > 0 && status !== 'running';

  return (
    <ToolWidgetRow
      chipText={status === 'running' ? null : fileName || 'memory'}
      expanded={expanded}
      failureText={getFailureReason(status, toolCall)}
      icon={Brain}
      onToggle={canExpand ? () => setExpanded((current) => !current) : undefined}
      status={status === 'stopped' ? 'error' : status}
      title={title}
    >
      <DiffView lines={diff} />
    </ToolWidgetRow>
  );
}
