import { useEffect } from 'react'
import { BackHandler, Dimensions } from 'react-native'
import { useImageViewer } from 'src/hooks/useImageViewer'
import { AnimatePresence, View } from 'tamagui'
import SaveableMedia from './SaveableMedia'
import ZoomableImage from './ZoomableImage'

// Single app-wide image viewer. One ZoomableImage lives behind this
// AnimatePresence branch; when `payload` goes null the subtree unmounts and
// the 6× useSharedValue + useAnimatedStyle inside ZoomableImage are released.
// Matches the V3 §14 constraint: the Reanimated surface exists only while
// the overlay is open, never per recycled feed cell.
//
// Shape mirrors ProfileHeader.tsx's audit-blessed avatar-zoom overlay
// (UI_TAMAGUI_HOLISTIC_AUDIT.md Rev 4 P1).
export default function ImageViewerOverlay() {
  const { payload, close } = useImageViewer()

  // Android hardware back dismisses the overlay without popping the current
  // screen. No-op on iOS where the button doesn't exist.
  useEffect(() => {
    if (!payload) return
    const sub = BackHandler.addEventListener('hardwareBackPress', () => {
      close()
      return true
    })
    return () => sub.remove()
  }, [payload, close])

  const { width, height } = Dimensions.get('window')

  return (
    <AnimatePresence>
      {payload ? (
        <View
          key="image-viewer"
          position="absolute"
          top={0}
          left={0}
          right={0}
          bottom={0}
          justifyContent="center"
          alignItems="center"
          backgroundColor="rgba(0,0,0,0.92)"
          zIndex={1000}
          transition="quick"
          enterStyle={{ opacity: 0 }}
          exitStyle={{ opacity: 0 }}
          opacity={1}
          onPress={close}
        >
          <SaveableMedia uri={payload.uri} kind="image">
            <ZoomableImage
              source={{ uri: payload.uri }}
              placeholder={payload.blurhash ? { blurhash: payload.blurhash } : null}
              style={{ width, height, backgroundColor: '#000' }}
              contentFit="contain"
            />
          </SaveableMedia>
        </View>
      ) : null}
    </AnimatePresence>
  )
}
