import { FlashList } from '@shopify/flash-list'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { ErrorBoundaryProps } from 'expo-router'
import { ActivityIndicator } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { ErrorState } from 'src/components/common/ErrorState'
import { Switch } from 'src/components/form/Switch'
import { useConfirmDialog } from 'src/hooks/useConfirmDialog'
import { updateAdminConfig } from 'src/lib/api'
import { adminQueries } from 'src/lib/queries/admin'
import { AccountStore } from 'src/state/accountStore'
import { Separator, Text, View, XStack, YStack } from 'tamagui'

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

export default function Screen() {
  const instance = AccountStore.activeAccount()?.instance
  const queryClient = useQueryClient()
  const { confirm, dialog: confirmDialog } = useConfirmDialog()

  const _handleUpdate = async (item: any, key: any, value: any) => {
    const ok = await confirm({
      title: 'Confirm',
      message: `Are you sure you want to ${value ? 'enable' : 'disable'} ${item.name}?`,
      confirmLabel: 'Confirm',
      destructive: true,
    })
    if (ok) {
      mutation.mutate({ key: key, value: value } as any)
    } else {
      queryClient.invalidateQueries({ queryKey: adminQueries.config().queryKey })
    }
  }

  const RenderItem = ({ item }: { item: any }) => {
    return (
      <XStack py="$3" px="$4" bg="white" justifyContent="space-between">
        <YStack maxWidth="60%" gap="$2">
          <Text fontSize="$5" fontWeight={'bold'}>
            {item.name}
          </Text>
          <Text fontSize="$3" color="$gray9">
            {item.description}
          </Text>
        </YStack>
        <Switch
          size="$3"
          defaultChecked={item.state}
          onCheckedChange={(checked) => _handleUpdate(item, item.key, checked)}
        >
          <Switch.Thumb transition="quicker" />
        </Switch>
      </XStack>
    )
  }

  const mutation = useMutation({
    mutationFn: (params: Record<string, any>) => {
      return updateAdminConfig(params)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: adminQueries.config().queryKey })
    },
  })

  const { data, status, error } = useQuery(adminQueries.config())

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

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

  return (
    <SafeAreaView edges={['top', 'bottom']}>
      <View bg="$accent" justifyContent="center" alignItems="center" p="$4">
        <Text fontSize="$5" color="$onAccent" fontWeight="bold" allowFontScaling={false}>
          {instance}
        </Text>
      </View>
      <FlashList
        data={data}
        extraData={data}
        renderItem={RenderItem}
        ItemSeparatorComponent={Separator}
      />
      {confirmDialog}
    </SafeAreaView>
  )
}
