import { useQuery } from '@tanstack/react-query'
import { type ErrorBoundaryProps, Link } from 'expo-router'
import { ActivityIndicator, Pressable } from 'react-native'
import { ErrorState } from 'src/components/common/ErrorState'
import UserAvatar from 'src/components/common/UserAvatar'
import ImageComponent from 'src/components/ImageComponent'
import { ScreenScrollContainer } from 'src/components/layout'
import { settingsQueries } from 'src/lib/queries/settings'
import { AccountStore } from 'src/state/accountStore'
import { Button, Group, Separator, Text, useTheme, View, XStack, YStack } from 'tamagui'
import { openBrowserAsync, prettyCount } from '../../../../utils'

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

export default function Screen() {
  const instance = AccountStore.activeAccount()?.instance
  const theme = useTheme()

  const gotoPrivacyPolicy = async () => {
    await openBrowserAsync(`https://${instance}/e/privacy`)
  }

  const gotoTermsOfService = async () => {
    await openBrowserAsync(`https://${instance}/e/terms`)
  }

  const gotoHelpCenter = async () => {
    await openBrowserAsync(`https://${instance}/site/help`)
  }

  const { data, isPending, error } = useQuery(settingsQueries.instanceV1())

  if (isPending) {
    return (
      <View flexGrow={1} mt="$5">
        <ActivityIndicator color={theme.color.val} />
      </View>
    )
  }

  if (error) {
    return (
      <View flexGrow={1}>
        <Text>Error</Text>
      </View>
    )
  }

  return (
    <ScreenScrollContainer variant="scroll" header="Instance">
      <YStack gap="$3">
        <ImageComponent
          source={{ uri: data.thumbnail }}
          style={{ width: '100%', height: 300 }}
          resizeMode={'cover' as any}
        />

        <View
          marginHorizontal="$3"
          p="$5"
          bg="$backgroundSecondary"
          borderRadius={20}
          marginTop={-50}
        >
          <Text fontSize="$7">{data.description}</Text>
        </View>

        <View marginHorizontal="$3" bg="$backgroundSecondary" borderRadius={20}>
          <Group orientation="horizontal">
            <Group.Item>
              <YStack
                flexGrow={1}
                p="$5"
                justifyContent="center"
                alignItems="center"
                gap="$2"
              >
                <Text fontSize="$8">{prettyCount(data.stats.user_count)}</Text>
                <Text color="$gray9">Total Users</Text>
              </YStack>
            </Group.Item>
            <Separator borderColor="$gray6" vertical />
            <Group.Item>
              <YStack
                flexGrow={1}
                p="$5"
                justifyContent="center"
                alignItems="center"
                gap="$2"
              >
                <Text fontSize="$8">{prettyCount(data.stats.status_count)}</Text>
                <Text color="$gray9">Total Posts</Text>
              </YStack>
            </Group.Item>
          </Group>
        </View>

        <View marginHorizontal="$3" bg="$backgroundSecondary" borderRadius={20}>
          <XStack p="$5" justifyContent="space-between" alignItems="center" gap="$3">
            <Text color="$gray9">Administrator Account</Text>
            <Link href={`/profile/${data?.contact_account?.id}`} asChild>
              <Pressable>
                <XStack alignItems="center" gap="$3">
                  <UserAvatar url={data?.contact_account?.avatar} size="sm" />
                  <Text fontSize="$7">@{data?.contact_account.username}</Text>
                </XStack>
              </Pressable>
            </Link>
          </XStack>
        </View>
        <View marginHorizontal="$3" bg="$backgroundSecondary" borderRadius={20}>
          <YStack p="$5">
            <Text color="$gray9" textAlign="center">
              Server Rules
            </Text>
            {data?.rules.map((rule: any, idx: any) => {
              return (
                <XStack key={idx} py="$3" pr="$3" gap="$3">
                  <Text fontWeight="bold" color="$gray8">
                    {rule.id}
                  </Text>
                  <Text>{rule.text}</Text>
                </XStack>
              )
            })}
          </YStack>
        </View>

        <View marginHorizontal="$3">
          <Button onPress={() => gotoPrivacyPolicy()} bg="$accent" size="$5">
            <Button.Text fontWeight="bold" color="$onAccent">
              Privacy Policy
            </Button.Text>
          </Button>
        </View>

        <View marginHorizontal="$3">
          <Button onPress={() => gotoTermsOfService()} bg="$accent" size="$5">
            <Button.Text fontWeight="bold" color="$onAccent">
              Terms of Service
            </Button.Text>
          </Button>
        </View>

        <View marginHorizontal="$3">
          <Button onPress={() => gotoHelpCenter()} bg="$accent" size="$5">
            <Button.Text fontWeight="bold" color="$onAccent">
              Help Center
            </Button.Text>
          </Button>
        </View>
      </YStack>
    </ScreenScrollContainer>
  )
}
