import { useAuth } from '@state/AuthProvider'
import { Image } from 'expo-image'
import { Link } from 'expo-router'
import { ActivityIndicator, Pressable } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { APP } from 'src/lib/branding'
import { emit } from 'src/lib/tapestry/emit'
import { appStorage, setTheme, uiKeys } from 'src/state/storage'
import { Button, Text, useTheme, View, XStack, YStack } from 'tamagui'

export default function Login() {
  const { isLoading, signOutAll } = useAuth()
  const theme = useTheme()

  // Long-press the icon to nuke local state — useful for development. The
  // multi-account "Sign out of all" path wipes every secret + every
  // per-account MMKV scope; appStorage (theme, etc.) is intentionally kept.
  const clearStorage = () => {
    void signOutAll()
  }

  const toggleTheme = () => {
    const curTheme = appStorage.getString(uiKeys.theme) || 'light'
    if (setTheme(curTheme === 'dark' ? 'light' : 'dark')) emit('T')
  }

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

  return (
    <SafeAreaView
      style={{
        backgroundColor: theme.background.val,
        flexGrow: 1,
      }}
      edges={['top', 'bottom']}
    >
      <YStack flexGrow={1} w="100%" px="$5">
        <YStack flexGrow={1} justifyContent="center" alignItems="center" gap="$5">
          <Pressable onPress={toggleTheme} onLongPress={clearStorage}>
            <Image
              source={require('../../../assets/icon.png')}
              style={{ width: 160, height: 160, borderRadius: 36 }}
              contentFit="contain"
            />
          </Pressable>
          <Text color="$color" fontSize="$11" fontWeight="200" letterSpacing={-1}>
            {APP.name}
          </Text>
        </YStack>

        <XStack gap="$3" mb="$5">
          <Link href="/handleLogin" asChild>
            <Button flex={1} size="$4">
              <Button.Text fontSize="$4" fontWeight="600">
                Login
              </Button.Text>
            </Button>
          </Link>

          <Link href="/handleSignup" asChild>
            <Button flex={1} size="$4" variant="outlined">
              <Button.Text fontSize="$4" fontWeight="600">
                Sign Up
              </Button.Text>
            </Button>
          </Link>
        </XStack>
      </YStack>
    </SafeAreaView>
  )
}
