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

import { themedColor } from '../../theme';
import { toolWidgetStyles } from './toolWidgetStyles';

/**
 * Uncontrolled disclosure. `collapsedTitle`/`expandedTitle` let the label
 * change with state like the web ("first code line…" → "Hide code").
 */
export function ExpandableSection({
  children,
  collapsedTitle,
  defaultExpanded = false,
  expandedTitle,
  monoTitle = false,
  titleStyle,
}: {
  children: ReactNode;
  collapsedTitle: string;
  defaultExpanded?: boolean;
  expandedTitle?: string;
  monoTitle?: boolean;
  titleStyle?: StyleProp<TextStyle>;
}) {
  const [expanded, setExpanded] = useState(defaultExpanded);
  const title = expanded ? (expandedTitle ?? collapsedTitle) : collapsedTitle;

  return (
    <View>
      <Pressable
        accessibilityRole="button"
        onPress={() => setExpanded((current) => !current)}
        style={toolWidgetStyles.sectionHeader}
      >
        <ChevronRight
          color={themedColor('#8E8E93')}
          size={14}
          strokeWidth={2.3}
          style={expanded ? toolWidgetStyles.sectionChevronOpen : toolWidgetStyles.sectionChevron}
        />
        <Text
          numberOfLines={1}
          style={titleStyle ?? (monoTitle ? toolWidgetStyles.sectionHeaderMonoText : toolWidgetStyles.sectionHeaderText)}
        >
          {title}
        </Text>
      </Pressable>
      {expanded ? <View style={toolWidgetStyles.sectionBody}>{children}</View> : null}
    </View>
  );
}
