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 { useScreenMenu, useSearchQuery } from 'src/components/menu'
import { useConfirmDialog } from 'src/hooks/useConfirmDialog'
import { postReportHandle, postUserHandle } 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 [query, setQuery] = useSearchQuery()
  useScreenMenu({
    title: 'Admin · Reports',
    intents: [
      {
        kind: 'search',
        placeholder: 'Filter reports',
        value: query,
        onChangeText: setQuery,
      },
    ],
  })
  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: async (update: any) => {
      if (activeReport?.object_type === 'App\\Status') {
        return postReportHandle(update)
      }
      if (activeReport?.object_type === 'App\\Profile') {
        return postUserHandle(update)
      }
    },
    onSuccess: () => {
      router.back()
    },
  })

  const _handleReport = async (type: any) => {
    if (type === 'delete') {
      const ok = await confirm({
        title: 'Confirm deletion',
        message: 'Are you sure you want to delete this?',
        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 RenderReportedAccount = () => (
    <YStack my="$3" alignItems="center" gap="$3">
      <Text color="$gray9">Reported account </Text>
      {activeReport?.object_type === 'App\\Status' ? (
        <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>
      ) : null}

      {activeReport?.object_type === 'App\\Profile' ? (
        <PressableOpacity onPress={() => gotoProfile(activeReport?.account?.id)}>
          <XStack bg="$gray4" p="$2" gap="$2" alignItems="center" borderRadius={10}>
            <UserAvatar url={activeReport?.account?.avatar} size="xs" />
            <Text fontWeight={'bold'}>
              {enforceLen(activeReport?.account?.acct, 15, true)}
            </Text>
          </XStack>
        </PressableOpacity>
      ) : null}
    </YStack>
  )

  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 reports!
        </Text>
      </YStack>
    </View>
  )

  const RenderItem = ({ item }: { item: any }) => {
    const objectType = item.object_type == 'App\\Status' ? 'post' : 'profile'
    if (objectType === 'post') {
      const _reportedBy = item?.reported_by_account?.username
      const msg = `#${item.id} - ${item.type} post report`
      return (
        <PressableOpacity onPress={() => handlePresentModalPress(item)}>
          <XStack
            p="$5"
            bg="$background"
            justifyContent="space-between"
            alignItems="center"
          >
            <Text fontWeight="$6" allowFontScaling={false}>
              {msg}
            </Text>
            <Text fontWeight="$5" allowFontScaling={false} color="$gray10">
              {timeAgo(item.created_at)}
            </Text>
          </XStack>
        </PressableOpacity>
      )
    }

    if (objectType === 'profile') {
      const _reportedBy = item?.reported_by_account?.username
      const msg = `#${item.id} - ${item.type} post report`
      return (
        <PressableOpacity onPress={() => handlePresentModalPress(item)}>
          <XStack
            p="$5"
            bg="$background"
            justifyContent="space-between"
            alignItems="center"
          >
            <Text fontWeight="$6" allowFontScaling={false}>
              {msg}
            </Text>
            <Text fontWeight="$5" allowFontScaling={false} color="$gray10">
              {timeAgo(item.created_at)}
            </Text>
          </XStack>
        </PressableOpacity>
      )
    }
  }

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

  const filteredReports = useMemo(() => {
    const q = query.trim().toLowerCase()
    if (!q || !Array.isArray(data)) return data
    return data.filter((item: any) => {
      const type = item?.type?.toLowerCase() ?? ''
      const reportedBy = item?.reported_by_account?.username?.toLowerCase() ?? ''
      return (
        type.includes(q) || reportedBy.includes(q) || String(item?.id ?? '').includes(q)
      )
    })
  }, [data, query])

  if (isPending) {
    return <ActivityIndicator />
  }

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

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

      <PixelfedBottomSheetModal
        ref={bottomSheetModalRef}
        index={1}
        snapPoints={snapPoints}
        backdropComponent={renderBackdrop}
      >
        <BottomSheetView style={{ flex: 1, margin: 20 }}>
          <XStack justifyContent="space-between" alignItems="center">
            <Text fontSize="$6" fontWeight="bold">
              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">
            <RenderReportedAccount />
            <YStack my="$3" alignItems="center" gap="$3">
              <Text color="$gray9">Reported by </Text>
              <PressableOpacity
                onPress={() => gotoProfile(activeReport?.reported_by_account?.id)}
              >
                <XStack bg="$gray4" p="$2" gap="$2" alignItems="center" borderRadius={10}>
                  <UserAvatar url={activeReport?.reported_by_account?.avatar} size="xs" />
                  <Text fontWeight={'bold'}>
                    {enforceLen(activeReport?.reported_by_account?.acct, 15, true)}
                  </Text>
                </XStack>
              </PressableOpacity>
            </YStack>
          </XStack>
          {activeReport?.object_type === 'App\\Status' ? (
            <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>
          ) : null}

          <Group mt="$5" orientation="vertical">
            <Group.Item>
              <Button flexGrow={1} size="$5" onPress={() => _handleReport('ignore')}>
                <Button.Text fontWeight="bold">Ignore</Button.Text>
              </Button>
            </Group.Item>
            {activeReport?.object_type === 'App\\Status' ? (
              <>
                <Separator borderColor="$gray2" />
                <Group orientation="horizontal">
                  <Group.Item>
                    <Button
                      flexGrow={1}
                      size="$5"
                      onPress={() => _handleReport('unlist')}
                    >
                      <Button.Text fontWeight="bold">Unlist Post</Button.Text>
                    </Button>
                  </Group.Item>
                  <Separator vertical borderColor="$gray4" />
                  <Group.Item>
                    <Button flexGrow={1} size="$5" onPress={() => _handleReport('cw')}>
                      <Button.Text fontWeight="bold">Mark Sensitive</Button.Text>
                    </Button>
                  </Group.Item>
                </Group>
              </>
            ) : null}
            {activeReport?.object_type === 'App\\Profile' ? (
              <>
                <Separator borderColor="$gray2" />
                <Group.Item>
                  <Button
                    flexGrow={1}
                    size="$5"
                    theme="red"
                    bg="$red9"
                    onPress={() => _handleReport('delete')}
                  >
                    <Button.Text color="$background" fontWeight="bold">
                      Delete Account
                    </Button.Text>
                  </Button>
                </Group.Item>
              </>
            ) : null}
          </Group>
        </BottomSheetView>
      </PixelfedBottomSheetModal>
      {confirmDialog}
    </SafeAreaView>
  )
}
