import type { NextPage } from 'next';
import { MainLayout } from '../layout/MainLayout';
import { Input } from '../../components/Input';
import { useForm } from 'react-hook-form';
import { Button } from '../../components/Button';
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import { Toolbar } from '../../components/Toolbar';
import { useFetchWithAuth } from '../../hooks/useFetchWithAuth';
import { Manytoone } from '../../components/Manytoone';
import { saveWithAuth } from '../../hooks/saveWithAuth';

const productoPage: NextPage = ()  => {

    const router = useRouter();
    const entityId: string = !!router.query.id ? router.query.id as string : "0";
    const baseUrl = process.env.API_URL;
    const { control, register, setValue,getValues,handleSubmit, formState: { isSubmitSuccessful, errors }  } = useForm(
        {
            defaultValues: {
                id: 0,
                nombre: '',
                codigo: '',
                precio: 0.00,
                creado: new Date()
            }
        }
    );
    
    const getInitData = async () => {
        if (!entityId || entityId=="0")
            return;
        const { data, error } = await useFetchWithAuth("producto/" + entityId);
        
        if (!error) {
            
            if (data.id!=0){
                setValue("id", data['id'])
                setValue("nombre", data['nombre'])
                setValue("codigo", data['codigo'])
                setValue("precio", Number(data["precio"]))
                setValue("creado",data["creado"])
            }

        } else {
            console.log(error)
        }
    }

    const onSubmit = async (entity: any) => {
        try {
            let endpoint = "producto";
            //entity['compania'] = {id: entity['compania']} (Ejemplo de conversion de manytoone)
            const { data, error } = await saveWithAuth(endpoint, entityId, entity);
            if (error) {
                console.log(error);
            } else {
                router.push("/"+endpoint+"/form"  + "?id=" + data.id)
            }
        } catch (e) {
            console.log("Post error:");
            console.table(e);
        }
    }


    useEffect(() => {
        getInitData();
    }, [router.query.id])

    return (
    <>
    <MainLayout title={'Compañia'}  >
        <Toolbar pathForm='/producto/form' pathList='/producto/' currentEntity={""} entityName='cliente'/>
        <div className='h-96 w-4/6 mx-auto p-4 border-solid border-gray-300 border-2 rounded-xl  '>
            <form onSubmit={handleSubmit(onSubmit)}
                >
                <Input id='id' label='' register={register} type='hidden'/>
                <Input id='nombre' label='Nombre' register={register}/>
                <Input id='codigo' label='Codigo' register={register}/>
                <Input id='precio' type='number' label='precio' register={register}/>
                <Input id='creado' type='datetime-local' label='creado' register={register}/>
                <Button type='submit' title='Guardar' />
                {errors?.root?.server && <p>Form submit failed.</p>}
            </form>            
        </div>
    </MainLayout>
    </>
    )
}

export default productoPage