import type { ComponentProps, ReactNode } from 'react'
import { type AccessibilityRole, type AccessibilityState, Pressable } from 'react-native'
import { YStack } from 'tamagui'
import { Card } from './Card'
import { FieldHelperText, FieldTitle } from './FieldText'

// Single primitive for the "Card + (title / description) + trailing slot"
// composition that the appearance / accessibility / compose / privacy /
// storage / notifications screens kept open-coding. The trailing slot is a
// `ReactNode` (Switch / chevron-with-value / radio-check / nothing), and an
// optional `onPress` wraps the row in a `Pressable` for tap-anywhere
// affordance. Geometry matches the cross-cutting convention so a screen can
// stack `SettingRow`s and `Separator`s without per-screen layout hacks.

type SettingRowProps = {
  title: string
  description?: string
  trailing?: ReactNode
  onPress?: () => void
  /** Accessibility wiring for the optional `Pressable` wrapper. */
  accessibility?: {
    role?: AccessibilityRole
    label?: string
    hint?: string
    state?: AccessibilityState
  }
  tone?: ComponentProps<typeof Card>['tone']
  /** Cap the title/description column so the trailing slot is never crowded
   *  by very long copy. Defaults to "75%" of the row width. */
  contentMaxWidth?: number | string
}

export function SettingRow({
  title,
  description,
  trailing,
  onPress,
  accessibility,
  tone = 'plain',
  contentMaxWidth = '75%',
}: SettingRowProps) {
  const body = (
    <Card
      tone={tone}
      flexDirection="row"
      justifyContent="space-between"
      alignItems="center"
    >
      <YStack flexShrink={1} maxWidth={contentMaxWidth as any} gap="$2" pr="$3">
        <FieldTitle>{title}</FieldTitle>
        {description ? <FieldHelperText>{description}</FieldHelperText> : null}
      </YStack>
      {trailing}
    </Card>
  )
  if (!onPress) return body
  return (
    <Pressable
      onPress={onPress}
      accessibilityRole={accessibility?.role}
      accessibilityLabel={accessibility?.label ?? title}
      accessibilityHint={accessibility?.hint ?? description}
      accessibilityState={accessibility?.state}
    >
      {body}
    </Pressable>
  )
}
