
import React, { FC, useEffect, useState } from 'react'
import { useFetchWithAuth } from '../../hooks/useFetchWithAuth';

import { Control, Controller, FieldValues, useFieldArray, useForm, UseFormRegister } from 'react-hook-form';

interface Props {
    attribute: string,
    keyRegiter?: any,
    control: Control<FieldValues, any>,
}

export const Manytooneform: FC<Props> = ({ attribute, keyRegiter, control }) => {
    if (!keyRegiter){
        keyRegiter=attribute;
    }
    const [data, setData] = useState([{id:0,nombre:'Select one', documentNumber: 0} ]);
    useEffect(() => {
        async function fetchData() {
            try {
                const { data, error } = await useFetchWithAuth(attribute.toLowerCase());
                setData(data);
            } catch (error) {
                console.error(error);
            }
        }
        fetchData();
    }, [attribute]);
    
    return (
        <div>
            <Controller key={keyRegiter}
                render={({ field }) => ( 
                <select key={keyRegiter+"select"} {...field} className="select select-xs select-primary">
                    <option key={keyRegiter+0} value={0}>
                            Seleccione un valor
                    </option>
                    {data.map((option) => (
                        <option key={keyRegiter+option.id} value={option.id}>
                            {option.nombre}
                        </option>
                    ))}
                </select>
                )}
                name={keyRegiter}
                control={control}
              />

        </div>
    )
}



