import { useWindowDimensions } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { BodyText, FootnoteText } from 'src/components/ui/Typography'
import { Toast, useToastState, YStack } from 'tamagui'

// Map the `preset` field on `ShowOptions` (originally a burnt-native field —
// `'error' | 'done' | 'none'`, plus our convenience alias `'success'`) to a
// Tamagui sub-theme name. Burnt's native code path is dead in this app
// (`<ToastProvider native={false}>` in `_layout.tsx`), but reusing the same
// field name means a call site that passes `preset: 'error'` gets a themed
// custom toast today and would still get the right native UX if the global
// `native` flag flipped tomorrow.
const PRESET_THEME: Record<string, 'red' | 'green' | undefined> = {
  error: 'red',
  done: 'green',
  success: 'green',
}

// Side gutter between the toast card and the screen edge.
const SIDE_GUTTER = 16
// Tablet/landscape ceiling — keeps the toast a card, not a banner.
const TABLET_MAX = 520

const GlobalToast = () => {
  const currentToast = useToastState()
  const { width: screenWidth } = useWindowDimensions()
  const insets = useSafeAreaInsets()
  if (!currentToast || currentToast.isHandledNatively) return null

  const themeName = PRESET_THEME[(currentToast as any).preset as string]

  // Explicit pixel width here works *with* `alignItems: center` on the
  // viewport (see _layout.tsx) — neither alone is sufficient.
  //
  // Tamagui's ToastImpl wraps every toast in an unstylable
  // `<AnimatedView style={{ margin: 'auto' }}>`. That wrapper is the actual
  // flex child of the viewport. `margin: 'auto'` does not horizontally
  // center on React Native. Without `alignItems: center` the viewport's
  // default column-stretch expands the AnimatedView edge-to-edge and the
  // toast sits left-aligned inside it. Without an explicit width on the
  // toast the AnimatedView would shrink to text width and we'd lose the
  // tablet ceiling. With both: the AnimatedView shrinks to `toastWidth`,
  // the viewport centers it, and the card is gutter-padded on both sides.
  //
  // Computed against the live window width minus safe-area insets
  // (notch/cutout/punch-hole) and the side gutter.
  const usableWidth = Math.max(
    0,
    screenWidth - insets.left - insets.right - SIDE_GUTTER * 2
  )
  const toastWidth = Math.min(TABLET_MAX, usableWidth)

  return (
    <Toast
      key={currentToast.id}
      duration={currentToast.duration}
      viewportName={currentToast.viewportName}
      theme={themeName}
      transition="quick"
      enterStyle={{ opacity: 0, y: 30, scale: 0.96 }}
      exitStyle={{ opacity: 0, y: 20, scale: 0.96 }}
      y={0}
      opacity={1}
      scale={1}
      width={toastWidth}
      paddingHorizontal="$4"
      paddingVertical="$3"
      borderRadius="$5"
      borderWidth={1}
      borderColor="$borderColor"
      // Solid surface so the toast remains legible over feed imagery.
      // The themed sub-themes (red/green) push this token into the
      // saturated step-6 range; the default theme falls back to the
      // standard background-secondary card surface.
      backgroundColor={themeName ? '$color6' : '$backgroundSecondary'}
      shadowColor="$shadowColor"
      shadowOffset={{ width: 0, height: 4 }}
      shadowOpacity={1}
      shadowRadius={12}
      elevation={6}
    >
      <YStack gap="$1">
        <BodyText
          emphasis="strong"
          textAlign="center"
          color={themeName ? '$colorInverse' : '$color'}
        >
          {currentToast.title}
        </BodyText>
        {!!currentToast.message && (
          <FootnoteText
            textAlign="center"
            color={themeName ? '$colorInverse' : '$colorSecondary'}
            opacity={themeName ? 0.92 : 1}
          >
            {currentToast.message}
          </FootnoteText>
        )}
      </YStack>
    </Toast>
  )
}

export default GlobalToast
