import { Spinner, Text, useTheme, View, XStack } from 'tamagui'

// Single discriminated union absorbs the pill's growing state space so
// future additions (P8b "Show N new replies" + "Refresh complete (+N)")
// land as state-construction changes in the post screen, not refactors
// in this component.
//
//   `idle`     — no walk in flight; the pill renders nothing.
//   `fetching` — the server's FetchAllRepliesJob is walking; show the
//                spinner + best-known descendants count.
//   `pending`  — (P8b) walk has produced new descendants we haven't
//                merged into the displayed list yet.
//   `complete` — (P8b) walk just finished; show the delta and let the
//                consumer auto-collapse to `idle`.
export type PillState =
  | { kind: 'idle' }
  | { kind: 'fetching'; resultCount?: number | null }
  | { kind: 'pending'; pendingCount: number }
  | { kind: 'complete'; delta: number }

export function FederatedRepliesPill({ state }: { state: PillState }) {
  const theme = useTheme()
  if (state.kind === 'idle') return null

  return (
    <View
      px="$3"
      py="$2.5"
      borderTopWidth={1}
      borderColor={theme.borderColor.val}
      backgroundColor={theme.background.val}
    >
      <XStack alignItems="center" gap="$2">
        {state.kind === 'fetching' ? (
          <>
            <Spinner size="small" color={theme.colorSecondary.val as string} />
            <Text fontSize="$3" color={theme.colorSecondary.val}>
              {state.resultCount && state.resultCount > 0
                ? `Fetching federated replies… (${state.resultCount} so far)`
                : 'Fetching federated replies…'}
            </Text>
          </>
        ) : null}
        {state.kind === 'pending' ? (
          <Text fontSize="$3" color={theme.colorSecondary.val}>
            {state.pendingCount === 1
              ? '1 new reply'
              : `${state.pendingCount} new replies`}
          </Text>
        ) : null}
        {state.kind === 'complete' ? (
          <Text fontSize="$3" color={theme.colorSecondary.val}>
            {state.delta > 0
              ? `Updated · +${state.delta}`
              : 'Federated replies up to date'}
          </Text>
        ) : null}
      </XStack>
    </View>
  )
}
