import React, { type ReactNode } from 'react';
import { Pressable, Text, View } from 'react-native';
import { ChevronRight, type LucideIcon } from 'lucide-react-native';

import { themedColor } from '../../theme';
import type { ToolWidgetStatus } from '../toolWidgetUtils';
import { StatusIcon } from './StatusIcon';
import { toolWidgetStyles } from './toolWidgetStyles';

// The header row every tool widget starts with — native analog of the web ToolUIBase.
export function ToolWidgetRow({
  accessibilityLabel,
  action,
  chipText,
  children,
  expanded,
  failureText,
  icon,
  note,
  onPress,
  onToggle,
  status,
  title,
}: {
  accessibilityLabel?: string;
  /** Right-aligned control in the header row (e.g. the artifact fullscreen button). */
  action?: ReactNode;
  chipText?: string | null;
  children?: ReactNode;
  expanded?: boolean;
  failureText?: string | null;
  icon: LucideIcon;
  note?: string | null;
  onPress?: () => void;
  onToggle?: () => void;
  status: ToolWidgetStatus;
  title: string;
}) {
  const canPress = Boolean(onPress || onToggle);

  return (
    <View style={toolWidgetStyles.row}>
      {/* The action sits OUTSIDE the toggle Pressable so it stays tappable
          when the row has no toggle (a disabled parent must never gate it). */}
      <View style={toolWidgetStyles.rowHeader}>
        <Pressable
          accessibilityLabel={accessibilityLabel}
          accessibilityRole={canPress ? 'button' : undefined}
          disabled={!canPress}
          onPress={onPress ?? onToggle}
          style={toolWidgetStyles.rowHeaderPressable}
        >
          <StatusIcon icon={icon} status={status} />
          <View style={toolWidgetStyles.rowHeaderContent}>
            <Text numberOfLines={1} style={toolWidgetStyles.rowTitle}>{title}</Text>
            {chipText ? (
              <View style={toolWidgetStyles.fileChip}>
                <Text numberOfLines={1} style={toolWidgetStyles.fileChipText}>{chipText}</Text>
              </View>
            ) : null}
            {note ? <Text numberOfLines={1} style={toolWidgetStyles.rowNote}>{note}</Text> : null}
            {canPress ? (
              <ChevronRight
                color={themedColor('#8E8E93')}
                size={15}
                strokeWidth={2.3}
                style={expanded ? toolWidgetStyles.rowChevronOpen : toolWidgetStyles.rowChevron}
              />
            ) : null}
          </View>
        </Pressable>
        {action ? <View style={toolWidgetStyles.rowAction}>{action}</View> : null}
      </View>
      {failureText ? (
        <View style={toolWidgetStyles.rowBody}>
          <Text style={toolWidgetStyles.rowFailureText}>{failureText}</Text>
        </View>
      ) : null}
      {expanded && children ? <View style={toolWidgetStyles.rowBody}>{children}</View> : null}
    </View>
  );
}
