import Feather from '@expo/vector-icons/Feather'
import { useLocalSearchParams, useRouter } from 'expo-router'
import { useRef, useState } from 'react'
import {
  ActivityIndicator,
  Keyboard,
  Pressable,
  type TextInput,
  TouchableWithoutFeedback,
} from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { Button, Form, Input, Text, useTheme, View, XStack, YStack } from 'tamagui'

export default function VerificationCodeScreen() {
  const router = useRouter()
  const { server } = useLocalSearchParams<{ server?: string }>()
  const theme = useTheme()

  const [email, setEmail] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const emailInputRef = useRef<TextInput>(null)

  const navigateBack = () => {
    router.back()
  }

  const handleSubmit = async () => {
    if (!email.trim()) {
      setError('Please enter your email address')
      emailInputRef.current?.focus()
      return
    }

    setLoading(true)
    setError('')

    try {
      router.push({
        pathname: '/verifyEmail',
        params: {
          domain: server ?? '',
          email,
          expires_in: '14400',
          status: 'success',
        },
      })
    } catch (_error) {
      setError('Network error. Please try again.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
      <SafeAreaView
        style={{
          backgroundColor: theme.background.val,
          flexGrow: 1,
        }}
        edges={['top']}
      >
        <YStack px="$4" pt="$4" pb="$6" gap="$4" flexGrow={1}>
          <XStack alignItems="center">
            <Pressable onPress={navigateBack}>
              <Feather name="arrow-left" size={24} color={theme.color.val} />
            </Pressable>
            <Text
              fontSize="$6"
              fontWeight="bold"
              color="$color"
              textAlign="center"
              flex={1}
            >
              Sign Up Verification
            </Text>
            <View width={24} />
          </XStack>

          <Form onSubmit={handleSubmit}>
            <YStack gap="$6" mt="$6">
              <YStack gap="$2">
                <Text fontSize="$5" fontWeight="bold" color="$color">
                  Enter verification details
                </Text>
                <Text color="$colorTertiary">
                  Please enter the email you used to sign up.
                </Text>
              </YStack>

              <YStack gap="$2">
                <Text color="$colorSecondary">Email address</Text>
                <Input
                  ref={emailInputRef as any}
                  size="$5"
                  placeholder="your@email.com"
                  value={email}
                  onChangeText={setEmail}
                  autoCapitalize="none"
                  keyboardType="email-address"
                  focusStyle={{ borderColor: '$borderColorStrong' }}
                />
              </YStack>

              {error ? (
                <Text color="$red10" fontSize="$4" textAlign="center">
                  {error}
                </Text>
              ) : null}

              <Form.Trigger asChild disabled={loading}>
                <Button size="$4" mt="$2">
                  {loading ? (
                    <ActivityIndicator />
                  ) : (
                    <Button.Text fontWeight="600">Verify Account</Button.Text>
                  )}
                </Button>
              </Form.Trigger>

              <YStack alignItems="center" gap="$2">
                <Text color="$colorTertiary" fontSize="$3" textAlign="center">
                  Didn't receive a code?
                </Text>
                <Pressable onPress={navigateBack}>
                  <Text color="$color" fontWeight="600" fontSize="$3">
                    Go back to signup and request a new code
                  </Text>
                </Pressable>
              </YStack>
            </YStack>
          </Form>
        </YStack>
      </SafeAreaView>
    </TouchableWithoutFeedback>
  )
}
