import { useContext, useEffect, useState } from 'react'
import { FlatList, Text } from 'react-native'
import { Button } from '../../components/Button';
import { Card } from '../../components/Card';
import { Input } from '../../components/Input';
import { useForm } from 'react-hook-form';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { useFetchWithAuth } from '../../hooks/useFetchWithAuth';
import { saveWithAuth } from '../../hooks/saveWithAuth';
import { ManyToOne } from '../../components/ManyToOne';
import { RootStackParams } from './SalesOrderStack';
import OneToMany from '../../components/OneToMany';
import { SalesOrderContext } from './SalesOrderContex';

interface Props extends NativeStackScreenProps<RootStackParams, 'SalesOrderFormScreen'> { };

export const SalesOrderFormScreen = ({ route, navigation }: Props) => {

    const {lines, setLines, add} = useContext(SalesOrderContext);

    const { control, handleSubmit, setValue, formState: { errors } } = useForm({
        defaultValues: {
            id: 0,
            numero: '',
            cliente: { id: 0 }
        }
    });

    let id: string = "0";
    if (route.params?.id != undefined) {
        id = String(route.params.id);
    }

    const getInitData = async () => {
        if (!id || id == "0")
            return;
        const { data, error } = await useFetchWithAuth("pedido/" + id);

        if (!error) {

            if (data.id != 0) {
                setValue("id", data['id'])
                setValue("numero", data['numero'])
                setValue("cliente", data['cliente'])
                const lines: SalesOrderLine[] = data['detalle'];
                setLines(lines);
            }

        } else {
            console.log(error)
        }
    }


    useEffect(() => {
        getInitData();
    }, [])

    const onSubmit = async (entity: any) => {
        try {
            let endpoint = "pedido";
            entity['cliente'] = { id: entity['cliente'].id }
            entity['detalle'] = lines;
            const { data, error } = await saveWithAuth(endpoint, id, entity);
            if (error) {
                console.log(error);
            } else {
                navigation.navigate("SalesOrderListScreen")
            }
        } catch (e) {
            console.log("Post error:");
            console.table(e);
        }
    }

    return (
        <>
            <FlatList

                data={[""]}
                renderItem={({ item }) =>
                    <>
                        <Card>
                            <Text className='text-xl text-center my-4'>Registro de Pedido</Text>
                            <Input name="numero" label='Número' control={control} />
                            <ManyToOne entity='cliente' columname='cliente' columnvalue="nombre" control={control} />
                            <OneToMany  />
                            <Button
                                title='Agrega produtos'
                                additionalStyle='mb-4'
                                onPress={() => navigation.navigate("ProductList" as never)} />
                            <Button
                                title='Guardar'
                                onPress={handleSubmit(onSubmit)}
                            />
                        </Card>
                    </>
                }
                keyExtractor={item2 => item2}
            />

        </>
    )
}