import {Pressable, View} from 'react-native'

import {Text} from '@/components/ui/typography'
import {useDelayedFlag} from '@/hooks/use-delayed-flag'
import {useOffline} from '@/lib/network'
import {atoms as a, pressed, useTheme} from '@/sprinkles'
import {SYNC_STATUS_DELAY_MS, useSyncState} from '@/stores/outbox'

// a subtle inline indicator of a scoped entity's offline-write state: queued to
// sync, or failed to sync. renders nothing once the write lands, so it's safe
// to drop into any row. scope is the outbox scope — a crumb id today, any
// aggregate root as more mutations opt in. pass onPress to make a failed badge
// tappable (a retry/discard prompt); omit it inside a row that's already a link
export const SyncBadge = ({
  scope,
  onPress,
}: {
  scope: string
  onPress?: () => void
}) => {
  const state = useSyncState(scope)
  const showPending = useDelayedFlag(
    state === 'pending',
    SYNC_STATUS_DELAY_MS,
  )
  const offline = useOffline()
  const t = useTheme()

  const failed = state === 'failed'
  if (!failed && !showPending) return null

  // offline, "syncing" would overpromise — nothing can move until the link
  // returns (exactly useOffline's sanctioned ambient-ui role)
  const label = failed
    ? 'Sync failed'
    : offline
      ? 'Waiting for connection'
      : 'Syncing…'
  const body = (
    <View
      style={[
        a.flex_row,
        a.align_center,
        a.gap_xs,
        a.py_xs,
        a.px_sm,
        a.rounded_md,
        {
          alignSelf: 'flex-start',
          backgroundColor: failed
            ? t.palette.negative_50
            : t.atoms.bg_contrast_25.backgroundColor,
        },
      ]}
    >
      <Text emoji style={a.text_xs}>
        {failed ? '⚠️' : '☁️'}
      </Text>
      <Text
        style={[
          a.text_xs,
          a.font_medium,
          failed
            ? {color: t.palette.negative_600}
            : t.atoms.text_contrast_medium,
        ]}
      >
        {label}
      </Text>
    </View>
  )

  if (!onPress) return body

  return (
    <Pressable
      onPress={onPress}
      accessibilityRole="button"
      accessibilityLabel={label}
      accessibilityHint="Retry or discard this change"
      hitSlop={8}
      style={({pressed: p}) => p && pressed}
    >
      {body}
    </Pressable>
  )
}
