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';
import { Onetomany } from '../../components/oneToMany/Onetomany';

const pedidoPage: 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,
                numero : 0,
                cliente: 0
            }
        }
    );
    
    const getInitData = async () => {
        if (!entityId || entityId=="0")
            return;
        const { data, error } = await useFetchWithAuth("pedido/" + entityId);
        
        if (!error) {
            
            if (data.id!=0){
                setValue("id", data['id'])
                setValue("numero", data['numero'])
                if (data['cliente'])
                    setValue("cliente", data['cliente'].id)
            }

        } else {
            console.log(error)
        }
    }

    const onSubmit = async (entity: any) => {
        try {
            let endpoint = "pedido";
            entity['cliente'] = {id: entity['cliente']} 
            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={'Pedido'}  >
        <Toolbar pathForm='/pedido/form' pathList='/pedido/' currentEntity={""} entityName='cliente'/>
        <div className='h-96 w-4/6 mx-auto p-4 border-solid border-gray-300 border-2 rounded-xl  '>
            <p className='text-center m-2'>
                Formulario <span className="text-primary">{"Pedidos"}</span>
            </p>
            <form onSubmit={handleSubmit(onSubmit)}
                >
                <Input id='id' label='' register={register} type='hidden'/>
                <Input id='numero' label='Numero' register={register}/>
                <Manytoone key={"cliente"} entity='cliente' control={control} />
                <Onetomany 
                    control={control} 
                    register={register} 
                    setValue={setValue} 
                    entityId={Number(entityId)} 
                    entityName={"pedido"} 
                    element={"detalle"} 
                    oneToManyHeader={[
                        {id:"producto",name:"ManyToOne"},
                        {id:"cantidad",name:"BigDecimal"},
                        {id:"precio",name:"BigDecimal"}]}
                />
                <Button type='submit' title='Guardar' />
                {errors?.root?.server && <p>Form submit failed.</p>}
            </form>            
        </div>
    </MainLayout>
    </>
    )
}

export default pedidoPage