import { useState, useCallback } from 'react'
import { z } from 'zod'

import { Button, Form, Input, YStack, Text } from '@junwon/aesthetics'

import { useRouterContext } from '../providers/RouterProvider'
import { useVisa } from '../providers/VisaProvider'

const signInSchema = z.object({
  email: z.string().email('Please enter a valid email address'),
})

export function SignIn() {
  const { setRoute } = useRouterContext()
  const [email, setEmail] = useState('')
  const [error, setError] = useState('')
  const [isSending, setIsSending] = useState(false)

  const { signIn, loading } = useVisa()

  const handleChangeText = useCallback((text: string) => {
    const noWhitespace = text.replace(/\s/g, '')
    setEmail(noWhitespace)
    setError('')
  }, [])

  const handleSubmit = async () => {
    try {
      const validated = signInSchema.parse({ email })
      setError('')
      setIsSending(true)
      const response = await signIn(validated.email, '/signin/verify')
      if (response.success) {
        setRoute('/signin/verify')
      } else {
        setError('Failed to sign in. Please try again or contact support.')
      }
    } catch (err) {
      if (err instanceof z.ZodError) {
        setError(err.errors[0].message)
      } else {
        console.log('SignIn error:', err)
        setError('Failed to send a verification email. Please try again.')
      }
    }
    setIsSending(false)
  }

  return (
    <YStack
      f={1}
      w="100%"
      px="$2.5"
      py="$2"
    >
      <Form onSubmit={handleSubmit}>
        <YStack gap="$3.5">
          <YStack gap="$2">
            <YStack px="$3">
              <Text
                col="$red10"
                als="center"
              >
                {error}
              </Text>
            </YStack>
            <Input
              placeholder="Email (e.g. junwon@junwon.com)"
              value={email}
              onChangeText={handleChangeText}
              autoCapitalize="none"
              keyboardType="email-address"
              returnKeyType="send"
              onSubmitEditing={handleSubmit}
              clearButtonMode="while-editing"
            />
          </YStack>
          <Form.Trigger asChild>
            <Button
              disabled={isSending || loading || !email}
              themeInverse={!isSending && !loading && !!email}
            >
              <Text>{isSending ? 'Sending...' : 'Sign In'}</Text>
            </Button>
          </Form.Trigger>
        </YStack>
      </Form>
    </YStack>
  )
}
