'use client'

import { FC } from 'react'
import { useBasicAuth } from 'hooks/useBasicAuth';
import { useRouter } from 'next/navigation'
import { useForm } from 'react-hook-form';
import Cookies from 'js-cookie';


interface Props {
}

export const Form:FC <Props> = () => {

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

    const onSubmit = async (entity: any) => {
        console.log("on submit")
        try {
            
            
            const { data, error } = await useBasicAuth("/login",getValues("user"),getValues("password") );
                        
            if (error) {
                console.log(error);
            } else {
                if (data && data.length>0){
                    Cookies.set("token",data);
                    router.push("/dashboard");
                }
            }
        } catch (e) {
            console.log("Post error:");
            console.table(e);
        }
    }
 return (
   <>
    <form onSubmit={handleSubmit(onSubmit)}>
                    <div className="form-control">
                    <label className="label">
                        <span className="label-text">Email</span>
                    </label>
                    <input 
                        type="text" 
                        placeholder="Usuario" 
                        className="input input-bordered" 
                        {...register("user")}/>
                    </div>
                    <div className="form-control">
                    <label className="label">
                        <span className="label-text">Password</span>
                    </label>
                    <input 
                        type="password" 
                        placeholder="password" 
                        className="input input-bordered" 
                        {...register("password")}
                    />
                    <label className="label">
                        <a href="#" className="label-text-alt link link-hover">Forgot password?</a>
                    </label>
                    </div>
                    <div className="form-control mt-6">
                    <button type="submit" className="btn btn-primary">Login</button>
                    </div>
                </form>   
   </>
 )
}