import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { FormProvider, useForm } from "react-hook-form";
import { AutocompleteInput, Button, Collection, Dialog, Input, Loader, } from "../../components";
import { personaService, } from "../docMockServices";
import { useEffect, useState } from "react";
import { useCrud } from "../../contexts";
import { useAsyncRequest } from "../../hooks";
export const ListCrudDocsContentEmpresasPersonasEditDialog = ({ isOpen, onClose, personaEmpresa, personasEnEmpresa, }) => {
    const { listar } = personaService;
    const { updateItem, createItem, extraData, fetchItems } = useCrud();
    const [personas, setPersonas] = useState([]);
    const listarPersonas = useAsyncRequest();
    useEffect(() => {
        listarPersonas.execute(listar).then((personas) => {
            setPersonas((personas || []).filter((persona) => !personasEnEmpresa.some((personaEnEmpresa) => personaEnEmpresa.idPersona === persona.id)));
        });
    }, [listar, personasEnEmpresa]);
    const methods = useForm({
        defaultValues: personaEmpresa,
    });
    const onSubmit = async (personaEmpresa) => {
        if (personaEmpresa.idEmpresa) {
            await updateItem.execute(personaEmpresa);
        }
        else {
            if (!extraData?.idEmpresa) {
                throw new Error("No se encontro el id de la empresa");
            }
            await createItem.execute({ ...personaEmpresa, idEmpresa: extraData.idEmpresa });
        }
        onClose();
        await fetchItems.execute();
    };
    return (_jsx(FormProvider, { ...methods, children: _jsx(Dialog, { isOpen: isOpen, onClose: onClose, title: "Editar Persona Empresa", footer: _jsxs(_Fragment, { children: [_jsx(Button, { variant: "outline", onClick: onClose, children: "Cancelar" }), _jsx(Button, { onClick: methods.handleSubmit(onSubmit), children: "Guardar" })] }), children: _jsx("form", { onSubmit: methods.handleSubmit(onSubmit), children: _jsxs(Collection, { children: [_jsx(AutocompleteInput, { label: "Persona", options: personas, getOptionLabel: (option) => option.nombre, getOptionValue: (option) => option.id.toString(), ...methods.register("idPersona", {
                                required: "Campo obligatorio",
                            }), error: methods.formState.errors.idPersona?.message, disabled: listarPersonas.isLoading || updateItem.isLoading || createItem.isLoading }), _jsx(Input, { label: "Cargo", ...methods.register("cargo", {
                                required: "Campo obligatorio",
                            }), error: methods.formState.errors.cargo?.message, disabled: listarPersonas.isLoading || updateItem.isLoading || createItem.isLoading }), _jsx(Loader, { isLoading: listarPersonas.isLoading || updateItem.isLoading || createItem.isLoading })] }) }) }) }));
};
