import { Feather } from '@expo/vector-icons'
import {
  BottomSheetBackdrop,
  type BottomSheetModal,
  BottomSheetView,
} from '@gorhom/bottom-sheet'
import { FlashList } from '@shopify/flash-list'
import { useMutation, useQuery } from '@tanstack/react-query'
import { type ErrorBoundaryProps, useRouter } from 'expo-router'
import { useCallback, useMemo, useRef, useState } from 'react'
import { ActivityIndicator } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { onMentionPressMethod } from 'src/components/common/AutolinkText'
import { PixelfedBottomSheetModal } from 'src/components/common/BottomSheets'
import { ErrorState } from 'src/components/common/ErrorState'
import { PressableOpacity } from 'src/components/common/PressableOpacity'
import StatusContent from 'src/components/common/StatusContent'
import UserAvatar from 'src/components/common/UserAvatar'
import { useConfirmDialog } from 'src/hooks/useConfirmDialog'
import { postAutospamHandle } from 'src/lib/api'
import { ICON } from 'src/lib/icons'
import { adminQueries } from 'src/lib/queries/admin'
import { enforceLen, timeAgo } from 'src/utils'
import { Button, Group, Separator, Text, useTheme, View, XStack, YStack } from 'tamagui'

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

export default function Screen() {
  const [activeReport, setActiveReport] = useState<any>()
  const router = useRouter()
  const theme = useTheme()
  const { confirm, dialog: confirmDialog } = useConfirmDialog()

  const bottomSheetModalRef = useRef<BottomSheetModal | null>(null)
  const snapPoints = useMemo(() => ['25%', '70%'], [])
  const handlePresentModalPress = useCallback((item: any) => {
    setActiveReport(item)
    bottomSheetModalRef.current?.present()
  }, [])
  const renderBackdrop = useCallback(
    (props: any) => (
      <BottomSheetBackdrop {...props} disappearsOnIndex={-1} appearsOnIndex={1} />
    ),
    []
  )

  const mutation = useMutation({
    mutationFn: (update: any) => {
      return postAutospamHandle(update)
    },
    onSuccess: () => {
      router.back()
    },
  })

  const _handleReport = async (type: any) => {
    if (['delete-post', 'delete-account'].includes(type)) {
      const msg = type === 'delete-post' ? 'delete this post?' : 'delete this account?'
      const ok = await confirm({
        title: 'Confirm',
        message: `Are you sure you want to ${msg}`,
        confirmLabel: 'Delete',
        destructive: true,
      })
      if (!ok) return
      bottomSheetModalRef.current?.close()
      mutation.mutate({ action: type, id: activeReport?.id })
      return
    }
    bottomSheetModalRef.current?.close()
    mutation.mutate({ action: type, id: activeReport?.id })
  }

  const gotoProfile = (id: string) => {
    bottomSheetModalRef.current?.close()
    router.push(`/profile/${id}`)
  }

  const gotoPost = (id: string) => {
    bottomSheetModalRef.current?.close()
    router.push(`/post/${id}`)
  }

  const gotoHashtag = (tag: string) => {
    bottomSheetModalRef.current?.close()
    router.push(`/hashtag/${tag}`)
  }

  const gotoMention = (username: string) => {
    bottomSheetModalRef.current?.close()
    router.push(`/profile/0?byUsername=${username}`)
  }

  const RenderEmpty = () => (
    <View flex={1}>
      <Separator borderColor="$borderColor" />
      <YStack flexGrow={1} justifyContent="center" alignItems="center" gap="$3">
        <Feather name="check-circle" size={ICON.xl} color={theme.colorTertiary.val} />
        <Text fontSize="$8" color="$gray9">
          No open autospam reports!
        </Text>
      </YStack>
    </View>
  )

  const RenderItem = ({ item }: { item: any }) => {
    const _msg = `#${item.id} - ${item.type}`
    return (
      <PressableOpacity onPress={() => handlePresentModalPress(item)}>
        <XStack
          px="$5"
          py="$3"
          bg="$background"
          justifyContent="space-between"
          alignItems="center"
        >
          <XStack alignItems="center" gap="$1">
            <Text fontWeight="$6" allowFontScaling={false}>
              #{item.id} -{' '}
            </Text>
            <UserAvatar url={item.status.account.avatar} size="sm" />
            <Text fontSize="$6" allowFontScaling={false} fontWeight="bold">
              @{item.status.account.username}
            </Text>
          </XStack>
          <Text fontWeight="$5" allowFontScaling={false} color="$gray10">
            {timeAgo(item.created_at)}
          </Text>
        </XStack>
      </PressableOpacity>
    )
  }

  const { isPending, isError, data, error } = useQuery(adminQueries.autospam())

  if (isPending) {
    return <ActivityIndicator />
  }

  if (isError) {
    return <Text>Error: {error.message}</Text>
  }

  return (
    <SafeAreaView style={{ flex: 1 }} edges={['top', 'bottom']}>
      <FlashList
        data={data}
        renderItem={RenderItem}
        contentContainerStyle={{ flex: 1 }}
        ItemSeparatorComponent={Separator}
        ListEmptyComponent={RenderEmpty}
      />

      <PixelfedBottomSheetModal
        ref={bottomSheetModalRef}
        index={1}
        snapPoints={snapPoints}
        backdropComponent={renderBackdrop}
      >
        {activeReport ? (
          <BottomSheetView style={{ flex: 1, margin: 20 }}>
            <XStack justifyContent="space-between" alignItems="center">
              <Text fontSize="$6" fontWeight="bold">
                Autospam Report #{activeReport?.id}
              </Text>
              <XStack gap="$1" alignItems="center">
                <Feather name="clock" color={theme.colorTertiary.val} />
                <Text fontWeight="bold" color="$gray9">
                  {timeAgo(activeReport?.created_at)}
                </Text>
              </XStack>
            </XStack>
            <XStack mb="$3" justifyContent="space-between" alignItems="center">
              <YStack my="$3" alignItems="center" gap="$3">
                <Text color="$gray9">Reported account </Text>
                <PressableOpacity
                  onPress={() => gotoProfile(activeReport?.status?.account?.id)}
                >
                  <XStack
                    bg="$gray4"
                    p="$2"
                    gap="$2"
                    alignItems="center"
                    borderRadius={10}
                  >
                    <UserAvatar url={activeReport?.status?.account?.avatar} size="xs" />
                    <Text fontWeight={'bold'}>
                      {enforceLen(activeReport?.status?.account?.acct, 15, true)}
                    </Text>
                  </XStack>
                </PressableOpacity>
              </YStack>
            </XStack>
            <View>
              <XStack justifyContent="space-between" alignItems="center" mb="$2">
                <Text color="$gray9">Reported Post</Text>
                <PressableOpacity onPress={() => gotoPost(activeReport?.status.id)}>
                  <Text color="$gray9">
                    Posted {timeAgo(activeReport?.status.created_at)}. Tap to view
                  </Text>
                </PressableOpacity>
              </XStack>
              <View
                borderWidth={1}
                px="$5"
                py="$5"
                borderColor="$gray5"
                borderRadius={10}
              >
                <StatusContent
                  html={activeReport?.status?.content ?? ''}
                  emojis={activeReport?.status?.emojis}
                  thresholdChars={280}
                  onHashtagPress={gotoHashtag}
                  onMentionPress={onMentionPressMethod(
                    gotoMention,
                    activeReport?.status?.account?.url ?? ''
                  )}
                />
              </View>
            </View>

            <Group mt="$5" orientation="vertical">
              <Group orientation="horizontal">
                <Group.Item>
                  <Button flexGrow={1} size="$5" onPress={() => _handleReport('dismiss')}>
                    <Button.Text fontWeight="bold">Mark as Spam</Button.Text>
                  </Button>
                </Group.Item>
                <Separator vertical borderColor="$gray4" />
                <Group.Item>
                  <Button flexGrow={1} size="$5" onPress={() => _handleReport('approve')}>
                    <Button.Text fontWeight="bold">Mark as not spam</Button.Text>
                  </Button>
                </Group.Item>
              </Group>
              <Separator borderColor="$gray2" />
              <Group orientation="horizontal">
                <Group.Item>
                  <Button
                    flexGrow={1}
                    size="$5"
                    onPress={() => _handleReport('dismiss-all')}
                  >
                    <Button.Text fontWeight="bold">Mark all as Spam</Button.Text>
                  </Button>
                </Group.Item>
                <Separator vertical borderColor="$gray4" />
                <Group.Item>
                  <Button
                    flexGrow={1}
                    size="$5"
                    onPress={() => _handleReport('approve-all')}
                  >
                    <Button.Text fontWeight="bold">Mark all as not spam</Button.Text>
                  </Button>
                </Group.Item>
              </Group>
              <Separator borderColor="$gray2" />
              <Group orientation="horizontal">
                <Group.Item>
                  <Button
                    flexGrow={1}
                    size="$5"
                    onPress={() => _handleReport('delete-post')}
                  >
                    <Button.Text fontWeight="bold">Delete Post</Button.Text>
                  </Button>
                </Group.Item>
                <Separator vertical borderColor="$gray4" />
                <Group.Item>
                  <Button
                    flexGrow={1}
                    size="$5"
                    onPress={() => _handleReport('delete-account')}
                  >
                    <Button.Text fontWeight="bold">Delete Account</Button.Text>
                  </Button>
                </Group.Item>
              </Group>
              {/* <Group.Item>
                        <Button flexGrow={1} size="$5" theme="red" fontWeight="bold">Delete Post</Button>
                    </Group.Item> */}
            </Group>
          </BottomSheetView>
        ) : null}
      </PixelfedBottomSheetModal>
      {confirmDialog}
    </SafeAreaView>
  )
}
