import {useRouter} from 'expo-router'
import {useIncomingShare} from 'expo-sharing'
import {useEffect, useRef} from 'react'
import {View} from 'react-native'

import {Layout} from '@/components/ui/layout'
import {Text} from '@/components/ui/typography'
import {setPendingShare, type PendingShare} from '@/lib/pending-share'
import {atoms as a, useTheme} from '@/sprinkles'
import {useAuth} from '@/stores/auth'

const isHttpUrl = (value: string) => /^https?:\/\//i.test(value)

type Payload = {shareType: string; value: string}

const toShare = (payloads: Payload[]): PendingShare | null => {
  const image = payloads.find(
    (p) => p.shareType === 'image' && p.value,
  )
  if (image) return {kind: 'image', uri: image.value}
  // urls can arrive typed as url or as plain shared text
  const url = payloads.find(
    (p) =>
      (p.shareType === 'url' || p.shareType === 'text') &&
      isHttpUrl(p.value),
  )
  if (url) return {kind: 'url', url: url.value.trim()}
  return null
}

export default function ExpoSharingScreen() {
  const t = useTheme()
  const router = useRouter()
  const user = useAuth((s) => s.user)
  const {sharedPayloads, isResolving, clearSharedPayloads} =
    useIncomingShare()
  const handled = useRef(false)

  useEffect(() => {
    if (handled.current || user === undefined) return
    if (user === null) {
      handled.current = true
      clearSharedPayloads()
      router.dismissTo('/sign-in')
      return
    }
    const share = toShare(sharedPayloads)
    if (!share && isResolving) return
    handled.current = true
    clearSharedPayloads()
    if (share) setPendingShare(share)
    router.replace(share ? '/screengrab' : '/')
  }, [user, sharedPayloads, isResolving, clearSharedPayloads, router])

  return (
    <Layout.Screen>
      <View
        style={[a.flex_1, a.justify_center, a.align_center, a.gap_lg]}
      >
        <Text style={t.atoms.text_contrast_medium}>
          Opening your share…
        </Text>
      </View>
    </Layout.Screen>
  )
}
