import { FC, useContext } from 'react'
import { Input } from '../../components/Input'
import { useForm } from 'react-hook-form';
import { Image, ScrollView, KeyboardAvoidingView, Text, View } from 'react-native';
import { InputPassword } from '../../components/InputPassword';
import { postBasicAuth } from '../../hooks/postBasicAuth';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Button } from '../../components/Button';
import { StackScreenProps } from '@react-navigation/stack';
import { AuthContext } from './AuthContext';
import { Background } from '../../components/Background';
import { Card } from '../../components/Card';


interface Props extends StackScreenProps<any, any> {

}

export const LoginScreen:FC <Props> = ({ navigation }) => {

  const {signIn, isAuthenticated} = useContext(AuthContext);
  const { control, handleSubmit, getValues, formState: { errors } } = useForm();

  const onSubmit = async () => {
    try {
        let url = "/login";
        
        const { data, error } = await postBasicAuth(url,getValues("user"),getValues("password") );
                    
        if (error) {
            console.log(error);
        } else {
            if (data && data.length>0){
                AsyncStorage.setItem("token",data);
                signIn();
                
            }
        }
    } catch (e) {
        console.log("Post error:");
        console.table(e);
    }
}

 return (
    <>
    
    <Background>
        
        <Image
                source={require('./logo.png')}
                className='my-8 self-center'
        />
        <Card addClassName='flex-1'>
            <Text className='my-6 text-center font-bold text-xl text-black'>Hola...</Text>
            <Input name="user" label='Usuario' control={control}/>
            
            <InputPassword name="password" label='Contraseña'  control={control}/>
            
            <Button additionalStyle='my-auto' onClick={handleSubmit(onSubmit)} title='Login'/>
        </Card>    
        
    </Background>
    

    </>
 )
}