import React, { useMemo, useState } from 'react';
import { Linking, Pressable, ScrollView, Text, View } from 'react-native';
import { ExternalLink, Search } from 'lucide-react-native';

import { isSafeUrl } from '../../features/conversation/markdownTextUtils';
import { themedColor } from '../../theme';
import type { SuperagentToolRendererProps } from '../../types';
import { ToolWidgetRow } from '../primitives/ToolWidgetRow';
import { toolWidgetStyles } from '../primitives/toolWidgetStyles';
import {
  extractSearchQuery,
  parseSearchResults,
  pluralize,
  prettifyUrl,
  truncateDisplayText,
  type SearchResultLink,
} from '../searchWidgetUtils';
import { getWidgetStatus } from '../toolWidgetUtils';

// web_search — native port of the web SearchWeb card (which serves search_web there).
export function SearchWebWidget({ toolCall }: SuperagentToolRendererProps) {
  const status = getWidgetStatus(toolCall.status);
  const query = useMemo(() => extractSearchQuery(toolCall), [toolCall]);
  const results = useMemo<SearchResultLink[]>(
    () => (status === 'success' ? parseSearchResults(toolCall.results) : []),
    [status, toolCall.results],
  );
  const [expanded, setExpanded] = useState(false);

  const hasResults = results.length > 0;
  const note = status === 'success' ? `Found ${pluralize(results.length, 'result')}` : null;

  return (
    <ToolWidgetRow
      chipText={query ? `"${truncateDisplayText(query)}"` : null}
      expanded={expanded}
      icon={Search}
      note={note}
      onToggle={hasResults ? () => setExpanded((current) => !current) : undefined}
      status={status}
      title={status === 'running' ? 'Searching for' : 'Searched for'}
    >
      <ScrollView nestedScrollEnabled style={toolWidgetStyles.linkListScroll}>
        <View style={toolWidgetStyles.linkList}>
          {results.map((result, index) => (
            <ResultLinkRow key={`${result.url}-${index}`} result={result} />
          ))}
        </View>
      </ScrollView>
    </ToolWidgetRow>
  );
}

function ResultLinkRow({ result }: { result: SearchResultLink }) {
  return (
    <Pressable
      accessibilityRole="link"
      onPress={() => {
        if (isSafeUrl(result.url)) Linking.openURL(result.url).catch(() => {});
      }}
      style={toolWidgetStyles.linkRow}
    >
      <ExternalLink color={themedColor('#8E8E93')} size={12} strokeWidth={2.3} style={toolWidgetStyles.linkRowIcon} />
      <Text numberOfLines={1} style={toolWidgetStyles.linkRowText}>
        {result.title || prettifyUrl(result.url)}
      </Text>
    </Pressable>
  );
}
