import type { BottomSheetModalProps } from '@gorhom/bottom-sheet'
import { BottomSheetModal, useBottomSheetModal } from '@gorhom/bottom-sheet'
import { type Ref, useCallback, useEffect, useState } from 'react'
import { BackHandler } from 'react-native'

export function PixelfedBottomSheetModal({
  ref,
  children,
  ...props
}: Omit<BottomSheetModalProps, 'onChange'> & { ref?: Ref<BottomSheetModal | null> }) {
  const [openPosition, setOpenPosition] = useState(-1)
  const { dismissAll } = useBottomSheetModal()

  const onBackPressed = useCallback(() => {
    if (openPosition < 0) {
      return false
    }

    dismissAll()
    return true
  }, [openPosition])

  const onChange = (index: number) => {
    setOpenPosition(index)
  }

  useEffect(() => {
    const backHandler = BackHandler.addEventListener('hardwareBackPress', onBackPressed)
    return () => backHandler.remove()
  }, [onBackPressed])

  return (
    <BottomSheetModal ref={ref} {...props} onChange={onChange}>
      {children}
    </BottomSheetModal>
  )
}
