import { Feather } from '@expo/vector-icons'
import { useQuery } from '@tanstack/react-query'
import type { ErrorBoundaryProps } from 'expo-router'
import { ActivityIndicator } from 'react-native'
import { ErrorState } from 'src/components/common/ErrorState'
import { ScreenScrollContainer } from 'src/components/layout'
import PushNotificationSettings from 'src/components/notifications/PushNotificationSettings'
import { useRequirePixelfed } from 'src/hooks/useRequirePixelfed'
import { ICON } from 'src/lib/icons'
import { notificationQueries } from 'src/lib/queries/notifications'
import { useActiveProfile } from 'src/state/AuthProvider'
import { openBrowserAsync } from 'src/utils'
import { Button, Text, View, YStack } from 'tamagui'

export function ErrorBoundary({ error, retry }: ErrorBoundaryProps) {
  return <ErrorState message={error.message} onRetry={retry} />
}

export default function Page() {
  // Mastodon Pass Phase 4 §5.2 / §8.3 — `pushCheck` calls into the Pixelfed-
  // only `api/v1.1/nag/state` endpoint. Mastodon push registration ships
  // gated to `pushUnavailable=true` for v1; redirect away rather than
  // rendering an error state.
  useRequirePixelfed()
  const { profile: userCache } = useActiveProfile()

  const { data: checkData, status, error } = useQuery(notificationQueries.pushCheck())
  if (status === 'pending') {
    return (
      <View>
        <ActivityIndicator />
      </View>
    )
  }

  if (status === 'error') {
    return (
      <View>
        <Text>{error}</Text>
      </View>
    )
  }

  const showMoreInfo = () => {
    openBrowserAsync('https://docs.pixelfed.org/running-pixelfed/push-notifications.html')
  }

  const RenderUnsupportedPanel = () => (
    <View flexGrow={1} justifyContent="center" alignItems="center">
      <View p="$7" flexShrink={1}>
        <YStack gap="$3" justifyContent="center" alignItems="center" flexGrow={1}>
          <Feather name="alert-triangle" size={ICON.empty} />
          <Text fontSize="$8" fontWeight="bold">
            Feature Unavailable
          </Text>
          <Text fontSize="$5">Please contact your instance admin for assistance.</Text>
        </YStack>
      </View>
      {userCache && userCache.is_admin ? (
        <View w={'100%'} p="$5" mb="$5" flexGrow={1}>
          <Button bg="$accent" size="$5" onPress={() => showMoreInfo()}>
            <Button.Text color="$onAccent">How to enable Push Notifications</Button.Text>
          </Button>
        </View>
      ) : null}
    </View>
  )

  const RenderSettings = () => {
    if (!checkData || !checkData['active']) {
      return <RenderUnsupportedPanel />
    }
    return <PushNotificationSettings />
  }

  return (
    <ScreenScrollContainer variant="scroll" header="Notifications">
      <RenderSettings />
    </ScreenScrollContainer>
  )
}
