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 updateAccountSchema = z.object({
  email: z.string().email('Please enter a valid email address'),
})

export function UpdateAccount() {
  const { setRoute } = useRouterContext()
  const [newEmail, setNewEmail] = useState('')
  const [error, setError] = useState('')
  const [isSending, setIsSending] = useState(false)

  const { profile, updateAccount, loading } = useVisa()

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

  const handleUpdateAccount = async () => {
    try {
      const validated = updateAccountSchema.parse({ email: newEmail })
      setError('')
      setIsSending(true)
      const response = await updateAccount({ email: validated.email }, '/account/update/verify')

      if (response.success) {
        setRoute('/account/update/verify')
      } else {
        setError('Failed to send a verification email. Please try again.')
      }
    } catch (err) {
      if (err instanceof z.ZodError) {
        setError(err.errors[0].message)
      } else {
        console.log('Update account error:', err)
        setError('Failed to send a verification email. Please try again.')
      }
    }
    setIsSending(false)
  }

  return (
    <YStack
      f={1}
      w="100%"
      px="$2.5"
      py="$5"
    >
      <Form onSubmit={handleUpdateAccount}>
        <YStack gap="$5">
          <YStack gap="$5">
            <YStack gap="$2">
              <Text fos="$4">Current Email</Text>
              <Input
                disabled
                value={profile.email || ''}
                placeholder="Current Email"
                bg="$gray3"
                h="$5"
                boc="transparent"
                br="$4"
                col="$gray10"
              />
            </YStack>

            <YStack gap="$2">
              <Text fos="$4">New Email</Text>
              <Input
                placeholder="Enter your new email address"
                value={newEmail}
                onChangeText={handleChangeText}
                autoCapitalize="none"
                keyboardType="email-address"
                returnKeyType="send"
                onSubmitEditing={handleUpdateAccount}
                clearButtonMode="while-editing"
                h="$5"
                bw={2}
                boc="$gray8"
                br="$4"
                focusStyle={{
                  boc: 'transparent',
                }}
              />
            </YStack>
          </YStack>

          <YStack gap="$2">
            <YStack px="$3">
              <Text
                col="$red10"
                als="center"
              >
                {error}
              </Text>
            </YStack>
            <Form.Trigger asChild>
              <Button
                disabled={isSending || loading || !newEmail || newEmail === profile.email}
                themeInverse={!isSending && !loading && !!newEmail && newEmail !== profile.email}
              >
                <Text>{isSending ? 'Sending...' : 'Change Email'}</Text>
              </Button>
            </Form.Trigger>
          </YStack>
        </YStack>
      </Form>
    </YStack>
  )
}
