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

import type { SuperagentToolRendererProps } from '../../types';
import { DiffView } from '../primitives/DiffView';
import { ToolWidgetRow } from '../primitives/ToolWidgetRow';
import {
  diffLinesFromNew,
  getStringArg,
  getToolFilePath,
  getWidgetStatus,
  humanizeFilePath,
  parseToolArgs,
} from '../toolWidgetUtils';

/**
 * write_file — native port of the web WriteFile card. Where the web offers a
 * "View Changes" server-side diff modal, native shows the written content
 * inline as an added-lines diff (the old content isn't available on-device).
 */
export function WriteFileWidget({ toolCall }: SuperagentToolRendererProps) {
  const args = useMemo(() => parseToolArgs(toolCall), [toolCall]);
  const status = getWidgetStatus(toolCall.status);
  const humanPath = humanizeFilePath(getToolFilePath(args));
  const content = getStringArg(args, ['content', 'file_text', 'code']);
  const diff = useMemo(() => (content ? diffLinesFromNew(content) : []), [content]);
  const [expanded, setExpanded] = useState(false);

  const title = status === 'running' ? 'Writing' : status === 'success' ? 'Wrote' : 'Write';
  // Same rejected note the web shows for a stopped, user-declined write.
  const rejected = status === 'stopped' && Boolean(toolCall.requires_user_input);
  const canExpand = diff.length > 0 && status !== 'running';

  return (
    <ToolWidgetRow
      chipText={humanPath !== 'file' ? humanPath : null}
      expanded={expanded}
      icon={FileText}
      note={rejected ? 'rejected' : null}
      onToggle={canExpand ? () => setExpanded((current) => !current) : undefined}
      status={status}
      title={title}
    >
      <DiffView lines={diff} />
    </ToolWidgetRow>
  );
}
