import {Redirect} from 'expo-router'
import {FunctionComponent, useState} from 'react'
import {View} from 'react-native'

import {useSignInWithEmail, useSignInWithGoogle} from '@/api/auth'
import useUser from '@/hooks/useUser'
import {Button, ButtonText} from '@/components/ui/button'
import {Input, InputField} from '@/components/ui/input'
import {Divider} from '@/components/ui/divider'

const Login: FunctionComponent = () => {
  const {mutate: signInWithSocialAuth} = useSignInWithGoogle()
  const {mutate: signInWithEmail} = useSignInWithEmail()

  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const user = useUser()

  if (user) {
    return <Redirect href="/(tabs)/account" />
  }

  return (
    <View className="mx-4 flex gap-4">
      <Input>
        <InputField value={email} onChangeText={setEmail} placeholder="Email" />
      </Input>
      <Input>
        <InputField value={password} onChangeText={setPassword} type="password" placeholder="Password" />
      </Input>
      <Button variant="outline" onPress={() => signInWithEmail({email, password})}>
        <ButtonText>Sign in</ButtonText>
      </Button>

      <Divider className="my-0.5" />

      <Button variant="outline" onPress={() => signInWithSocialAuth()}>
        <ButtonText>Sign in with Google</ButtonText>
      </Button>
    </View>
  )
}

export default Login
