import { Feather } from '@expo/vector-icons'
import { useQuery } from '@tanstack/react-query'
import { type ErrorBoundaryProps, useLocalSearchParams, useRouter } from 'expo-router'
import { ActivityIndicator, Pressable } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { ErrorState } from 'src/components/common/ErrorState'
import { PressableOpacity } from 'src/components/common/PressableOpacity'
import UserAvatar from 'src/components/common/UserAvatar'
import { ICON } from 'src/lib/icons'
import { adminQueries } from 'src/lib/queries/admin'
import { AccountStore } from 'src/state/accountStore'
import { enforceLen, formatTimestamp, openExternalUrl, prettyCount } from 'src/utils'
import {
  Button,
  Group,
  ScrollView,
  Separator,
  Text,
  useTheme,
  useToastController,
  View,
  XStack,
  YStack,
} from 'tamagui'

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

export default function Screen() {
  const { id } = useLocalSearchParams<{ id: string }>()
  const router = useRouter()
  const instance = AccountStore.activeAccount()?.instance
  const toast = useToastController()
  const theme = useTheme()

  const gotoProfile = () => {
    const pid = account?.data.profile_id
    router.navigate(('/profile/' + pid) as any)
  }

  const gotoManage = () => {
    const pid = account?.data.id
    const url = `https://${instance}/i/admin/users/show/${pid}`
    void openExternalUrl(url)
  }

  const RenderUserCard = () => (
    <View px="$5" py="$3" bg="$backgroundSecondary" borderRadius={10}>
      <XStack alignItems="center" gap="$3" justifyContent="space-between">
        <XStack alignItems="center" gap="$3">
          <UserAvatar url={account?.data.avatar} size="sm" />
          <YStack gap={5}>
            <XStack alignItems="center" gap="$2">
              <Text fontSize="$6" fontWeight={'bold'}>
                @{account?.data.username}
              </Text>
              {account?.data.is_private ? (
                <XStack gap="$1">
                  <Feather name="lock" color="red" />
                  <Text color="red">Private Account</Text>
                </XStack>
              ) : null}
            </XStack>
            <YStack>
              <Text color="$gray9">{account?.data.name}</Text>
            </YStack>
          </YStack>
        </XStack>
        <PressableOpacity onPress={() => gotoProfile()}>
          <Text color="$accent" fontWeight={'bold'}>
            View
          </Text>
        </PressableOpacity>
      </XStack>
    </View>
  )

  const RenderListItem = ({ title, value }: { title: any; value: any }) => (
    <Group.Item>
      <XStack flexGrow={1} p="$3" justifyContent="space-between">
        <Text color="$gray10">{title}</Text>
        <Text fontWeight="bold">{value}</Text>
      </XStack>
    </Group.Item>
  )

  const RenderListItemCheck = ({
    title,
    value,
    onPressValue,
  }: {
    title: any
    value: any
    onPressValue: any
  }) => (
    <Group.Item>
      <XStack flexGrow={1} p="$3" justifyContent="space-between" alignItems="center">
        <Text color="$gray10">{title}</Text>
        <Pressable onPress={() => toast.show(title, { message: onPressValue })}>
          <XStack gap={5} alignItems="center">
            <Text fontWeight="bold">{value}</Text>
            <Feather name="check-circle" color={theme.colorSuccess.val} size={ICON.sm} />
          </XStack>
        </Pressable>
      </XStack>
    </Group.Item>
  )

  const { data: account, status, error } = useQuery(adminQueries.user(id))

  if (status === 'pending') {
    return <ActivityIndicator />
  }

  if (status === 'error') {
    return <Text>{error?.message}</Text>
  }

  return (
    <SafeAreaView edges={['top', 'bottom']}>
      <ScrollView>
        <YStack p="$3" gap="$2">
          <RenderUserCard />

          <YStack bg="$backgroundSecondary" borderRadius={10} overflow="hidden">
            <Group orientation="horizontal">
              <RenderListItem
                title="Posts"
                value={prettyCount(account?.data.statuses_count)}
              />
              <Separator borderColor="$gray2" vertical />
              <RenderListItem
                title="Followers"
                value={prettyCount(account?.data.followers_count)}
              />
              <Separator borderColor="$gray2" vertical />
              <RenderListItem
                title="Following"
                value={prettyCount(account?.data.following_count)}
              />
            </Group>
          </YStack>
          <YStack bg="$backgroundSecondary" borderRadius={10} overflow="hidden">
            <Group orientation="vertical">
              {account?.data.email_verified_at ? (
                <RenderListItemCheck
                  title="Email"
                  value={enforceLen(account?.data.email, 40, true)}
                  onPressValue={account?.data.email}
                />
              ) : (
                <RenderListItem
                  title="Email"
                  value={enforceLen(account?.data.email, 40, true)}
                />
              )}
              <Separator borderColor="$gray2" />
              <Group orientation="horizontal">
                <RenderListItem
                  title="Joined"
                  value={formatTimestamp(account?.data.created_at)}
                />
                {account?.data.last_active_at ? (
                  <>
                    <Separator borderColor="$gray2" vertical />
                    <RenderListItem
                      title="Active"
                      value={formatTimestamp(account?.data.last_active_at)}
                    />
                  </>
                ) : null}
              </Group>

              {account?.meta.account.website ? (
                <>
                  <Separator borderColor="$gray2" />
                  <RenderListItem
                    title="Website"
                    value={enforceLen(account?.meta.account.website, 25, true)}
                  />
                </>
              ) : null}

              {account?.meta.account.note_text ? (
                <>
                  <Separator borderColor="$gray2" />
                  <RenderListItem
                    title="Bio"
                    value={enforceLen(account?.meta.account.note_text, 25, true)}
                  />
                </>
              ) : null}
            </Group>
          </YStack>
          <Button theme="red" bg="$red9" onPress={() => gotoManage()}>
            <Button.Text color="$onAccent" fontWeight="bold">
              Manage Account
            </Button.Text>
          </Button>
        </YStack>
      </ScrollView>
    </SafeAreaView>
  )
}
