import React, { useMemo, useState } from 'react';
import { Pressable, Text, View } from 'react-native';
import { ChevronRight, ImageIcon } from 'lucide-react-native';

import { conversationStyles } from '../conversation/conversationStyles';
import { ImageGallery } from '../../components/ImageGallery';
import { parseSentImages } from './sendImage';
import { themedColor } from '../../theme';
import type { SuperagentToolCall } from '../../types';

/** Renders one or more `send_image` tool calls as actual images via the generic
 *  `ImageGallery` (single inline / grid + lightbox), under a "Sent N images"
 *  header. Mirrors the web superagent's SendImageGallery widget.
 *
 *  When `defaultCollapsed` is set (the agent already pasted the same images into
 *  the message text), the gallery renders collapsed behind a tappable header so
 *  the images aren't shown twice — but they stay reachable rather than hidden. */
export function SendImageGallery({
  toolCalls,
  defaultCollapsed = false,
}: {
  toolCalls: SuperagentToolCall[];
  defaultCollapsed?: boolean;
}) {
  const images = useMemo(() => parseSentImages(toolCalls), [toolCalls]);
  // Collapsed by default when redundant with the message text; null until the
  // user taps the header, after which their choice wins over the default.
  const [expandedOverride, setExpandedOverride] = useState<boolean | null>(null);
  const expanded = expandedOverride ?? !defaultCollapsed;

  if (images.length === 0) return null;

  const headerLabel = images.length === 1 ? 'Sent an image' : `Sent ${images.length} images`;

  return (
    <View style={conversationStyles.sendImageWrap}>
      <Pressable
        accessibilityRole={defaultCollapsed ? 'button' : undefined}
        disabled={!defaultCollapsed}
        onPress={() => setExpandedOverride(!expanded)}
        style={conversationStyles.sendImageHeader}
      >
        <ImageIcon color={themedColor('#8E8E93')} size={14} strokeWidth={2.2} />
        <Text style={conversationStyles.sendImageHeaderText}>{headerLabel}</Text>
        {defaultCollapsed ? (
          <ChevronRight
            color={themedColor('#8E8E93')}
            size={14}
            strokeWidth={2.3}
            style={expanded ? conversationStyles.toolTimelineChevronOpen : conversationStyles.toolTimelineChevron}
          />
        ) : null}
      </Pressable>

      {expanded ? <ImageGallery images={images} /> : null}
    </View>
  );
}
