import UserAvatar from '@components/common/UserAvatar'
import { Feather } from '@expo/vector-icons'
import { useQuery } from '@tanstack/react-query'
import type { ErrorBoundaryProps } from 'expo-router'
import { useLocalSearchParams } from 'expo-router'
import { ActivityIndicator } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { ErrorState } from 'src/components/common/ErrorState'
import { ICON } from 'src/lib/icons'
import { accountQueries } from 'src/lib/queries/accounts'
import { formatTimestamp, formatTimestampMonthYear, getDomain } from 'src/utils'
import { ScrollView, Text, useTheme, View, XStack, YStack } from 'tamagui'

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

export default function ProfileScreen() {
  const { id } = useLocalSearchParams<{ id: string }>()
  const theme = useTheme()

  const {
    data: user,
    error: userError,
    isFetching: isFetchingUser,
  } = useQuery(accountQueries.byId(id))

  const userId = user?.id
  const { data: relationship } = useQuery({
    ...accountQueries.relationship(userId!),
    enabled: !!userId,
  })

  if (userError) {
    return (
      <SafeAreaView
        edges={['top', 'bottom']}
        style={{ flex: 1, backgroundColor: theme.background.val }}
      >
        <View flexGrow={1} justifyContent="center" alignItems="center" p="$5">
          <YStack alignItems="center" gap="$2">
            <Text fontSize="$8" color={theme.color.val}>
              Oops, an error occurred!
            </Text>
            <Text fontSize="$5" color={theme.colorSecondary.val}>
              Please try again later
            </Text>
          </YStack>
        </View>
      </SafeAreaView>
    )
  }

  if (isFetchingUser) {
    return (
      <SafeAreaView
        edges={['top', 'bottom']}
        style={{ flex: 1, backgroundColor: theme.background.val }}
      >
        <View flexGrow={1} justifyContent="center" alignItems="center">
          <ActivityIndicator color={theme.color.val} />
        </View>
      </SafeAreaView>
    )
  }

  return (
    <SafeAreaView
      edges={['top', 'bottom']}
      style={{ flex: 1, backgroundColor: theme.background.val }}
    >
      <ScrollView
        contentContainerStyle={{
          padding: '$5',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        <YStack
          justifyContent="center"
          alignItems="center"
          gap="$4"
          flexWrap="wrap"
          mb="$5"
        >
          <UserAvatar url={user?.avatar} size="lg" />
          <YStack justifyContent="center" alignItems="center" gap="$1" flexWrap="wrap">
            <Text fontSize="$7" fontWeight="bold" flexWrap="wrap" color={theme.color.val}>
              {user?.acct}
            </Text>
            <Text fontSize="$5" color={theme.colorTertiary.val}>
              {user?.url.replaceAll('https://', '')}
            </Text>
            <Text
              fontSize="$3"
              mt="$3"
              px="$3"
              textAlign="center"
              color={theme.colorTertiary.val}
            >
              To help keep our community authentic, we're showing information about
              accounts on this server and other fediverse servers.
            </Text>
          </YStack>
        </YStack>

        <YStack
          w="100%"
          justifyContent="flex-start"
          alignItems="flex-start"
          gap="$6"
          my="$3"
          pr="$10"
        >
          {user?.is_admin ? (
            <XStack justifyContent="flex-start" alignItems="flex-start" gap="$4">
              <Feather name="shield" size={ICON.xl} color={theme.colorTertiary.val} />
              <YStack gap={3}>
                <Text
                  fontSize="$6"
                  fontWeight={600}
                  fontFamily="$body"
                  color={theme.color.val}
                >
                  Admin Account
                </Text>
                <Text fontSize="$5" color={theme.colorSecondary.val}>
                  This is an admin of{' '}
                  <Text fontWeight="bold" color={theme.colorSecondary.val}>
                    {getDomain(user?.url)}
                  </Text>
                </Text>
              </YStack>
            </XStack>
          ) : null}
          {user?.locked ? (
            <XStack justifyContent="flex-start" alignItems="flex-start" gap="$4">
              <Feather name="lock" size={ICON.xl} color={theme.colorTertiary.val} />
              <YStack gap={3}>
                <Text
                  fontSize="$6"
                  fontWeight={600}
                  fontFamily="$body"
                  color={theme.color.val}
                >
                  Private Account
                </Text>
                <Text fontSize="$5" color={theme.colorSecondary.val}>
                  Curates who can follow them and see their posts
                </Text>
              </YStack>
            </XStack>
          ) : null}
          <XStack justifyContent="flex-start" alignItems="flex-start" gap="$4">
            <Feather name="calendar" size={ICON.xl} color={theme.colorTertiary.val} />
            <YStack gap={3}>
              <Text
                fontSize="$6"
                fontWeight={600}
                fontFamily="$body"
                color={theme.color.val}
              >
                Account created
              </Text>
              <Text fontSize="$5" color={theme.colorSecondary.val}>
                {formatTimestampMonthYear(user?.created_at)}
              </Text>
            </YStack>
          </XStack>
          {relationship?.following ? (
            <XStack justifyContent="flex-start" alignItems="flex-start" gap="$4">
              <Feather name="user-plus" size={ICON.xl} color={theme.colorTertiary.val} />
              <YStack gap={3}>
                <Text
                  fontSize="$6"
                  fontWeight={600}
                  fontFamily="$body"
                  color={theme.color.val}
                >
                  Relationship Status
                </Text>
                {relationship?.following_since ? (
                  <Text fontSize="$5" color={theme.colorSecondary.val}>
                    You've followed this account since{' '}
                    <Text
                      color="$gray10"
                      fontSize="$5"
                      fontWeight={600}
                      fontFamily="$body"
                    >
                      {formatTimestampMonthYear(relationship.following_since)}
                    </Text>
                  </Text>
                ) : (
                  <Text fontSize="$5" color={theme.colorSecondary.val}>
                    You're following this account
                  </Text>
                )}
              </YStack>
            </XStack>
          ) : null}
          {relationship?.followed_by ? (
            <XStack justifyContent="flex-start" alignItems="flex-start" gap="$4">
              <Feather name="users" size={ICON.xl} color={theme.colorTertiary.val} />
              <YStack gap={3}>
                <Text
                  fontSize="$6"
                  fontWeight={600}
                  fontFamily="$body"
                  color={theme.color.val}
                >
                  Follower Status
                </Text>
                <Text fontSize="$5" color={theme.colorSecondary.val}>
                  This account is following you
                </Text>
              </YStack>
            </XStack>
          ) : null}
          <XStack justifyContent="flex-start" alignItems="flex-start" gap="$4">
            <Feather name="server" size={ICON.xl} color={theme.colorTertiary.val} />
            <YStack gap={3}>
              <Text
                fontSize="$6"
                fontWeight={600}
                fontFamily="$body"
                color={theme.color.val}
              >
                Server
              </Text>
              <Text fontSize="$5" color={theme.colorSecondary.val}>
                {getDomain(user?.url)}
              </Text>
            </YStack>
          </XStack>
          {user?.discoverable ? (
            <XStack justifyContent="flex-start" alignItems="flex-start" gap="$4">
              <Feather name="compass" size={ICON.xl} color={theme.colorTertiary.val} />
              <YStack gap={3}>
                <Text
                  fontSize="$6"
                  fontWeight={600}
                  fontFamily="$body"
                  color={theme.color.val}
                >
                  Discoverable
                </Text>
                <Text fontSize="$5" color={theme.colorSecondary.val}>
                  Posts from this account may appear in search results
                </Text>
              </YStack>
            </XStack>
          ) : null}
          {user?.pronouns && user?.pronouns.length ? (
            <XStack justifyContent="flex-start" alignItems="flex-start" gap="$4">
              <Feather name="user" size={ICON.xl} color={theme.colorTertiary.val} />
              <YStack gap={3}>
                <Text
                  fontSize="$6"
                  fontWeight={600}
                  fontFamily="$body"
                  color={theme.color.val}
                >
                  Pronouns
                </Text>
                <Text fontSize="$5" color={theme.colorSecondary.val}>
                  {user.pronouns.join(', ')}
                </Text>
              </YStack>
            </XStack>
          ) : null}
          {user?.local == false && user?.last_fetched_at ? (
            <XStack justifyContent="flex-start" alignItems="flex-start" gap="$4">
              <Feather name="clock" size={ICON.xl} color={theme.colorTertiary.val} />
              <YStack gap={3}>
                <Text
                  fontSize="$6"
                  fontWeight={600}
                  fontFamily="$body"
                  color={theme.color.val}
                >
                  Last fetched at
                </Text>
                <Text fontSize="$5" color={theme.colorSecondary.val}>
                  Account was last updated {formatTimestamp(user?.last_fetched_at)}
                </Text>
              </YStack>
            </XStack>
          ) : null}
        </YStack>
      </ScrollView>
    </SafeAreaView>
  )
}
