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

import type { SuperagentToolRendererProps } from '../../types';
import { getScreenshotState } from '../mediaWidgetUtils';
import { ImageGrid } from '../primitives/ImageGrid';
import { ToolWidgetRow } from '../primitives/ToolWidgetRow';

/**
 * browserbase_screenshot / local_browser_screenshot — native port of the web
 * BrowserbaseScreenshot card: a status row that, once the image_url result
 * lands, becomes a toggleable row revealing the screenshot with a tap-to-zoom
 * lightbox (the native stand-in for the web's click-to-open-tab image).
 */
export function BrowserbaseScreenshotWidget({ toolCall }: SuperagentToolRendererProps) {
  // The web browserbase card starts expanded.
  const [expanded, setExpanded] = useState(true);
  // Memoized: extracting the image URL JSON-parses the (potentially large)
  // screenshot results string.
  const { imageUrl, phase } = useMemo(() => getScreenshotState(toolCall), [toolCall]);

  if (phase === 'ready' && imageUrl) {
    return (
      <ToolWidgetRow
        expanded={expanded}
        icon={Camera}
        onToggle={() => setExpanded((current) => !current)}
        status="success"
        title="Screenshot"
      >
        <ImageGrid images={[{ url: imageUrl }]} />
      </ToolWidgetRow>
    );
  }

  const title = phase === 'error' ? 'Screenshot failed' : phase === 'taken' ? 'Screenshot taken' : 'Taking screenshot';
  const status = phase === 'taken' ? 'success' : phase === 'error' ? 'error' : 'running';

  return <ToolWidgetRow icon={Camera} status={status} title={title} />;
}
