import type { NextPage } from 'next';
import Image from 'next/image';
import { Input } from '../../components/Input';
import { Button } from '../../components/Button';
import { useForm } from 'react-hook-form';
import { useRouter } from 'next/router';
import { postBasicAuth } from '../../hooks/postBasicAuth';
import Cookies from 'js-cookie';

const indexPage: NextPage = () => {

    const router = useRouter();
    
    const { register, handleSubmit, getValues, formState: { errors } } = useForm();

    const onSubmit = async (entity: any) => {
        console.log("on submit")
        try {
            let url = process.env.API_URL + "/login";   
            const { data, error } = await postBasicAuth(url,getValues("user"),getValues("password") );
                        
            if (error) {
                console.log(error);
            } else {
                if (data && data.length>0){
                    Cookies.set("token",data);
                    router.push("/home");
                }
            }
        } catch (e) {
            console.log("Post error:");
            console.table(e);
        }
    }

    return (

    <div className='flex flex-col items-center'>
        <Image alt="Logo" 
            src={"/logo.png"} 
            width={100} 
            height={100} 
        />
        <form onSubmit={handleSubmit(onSubmit)}>
            <div className='flex flex-col'>
                <Input id="user" label='Usuario' register={register} />
                {errors.User && <span>This field is required</span>}
                <Input id="password" label='Contraseña'  type="password" register={register}/>
            </div>
            <Button type='submit' onClick={()=>{console.log("login")}} title='Login'/>
        </form>

    </div>

    )
}

export default indexPage	