import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Button } from '@citric/core';
import { useCallback, useMemo, useRef, useState } from 'react';
import { FieldRenderer } from '../index.js';
import { JinjaRawContext, useJinjaContext } from '../../context/JinjaContext.js';
import { buildFields } from '../../form/field-builder.js';
import { FormContextValue } from '../../form/FormContextValue.js';
function getFirstVariableOfContext(context) {
    const keys = Object.keys(context.variables);
    const variables = context.variables[keys[0]];
    return variables[0];
}
function createFormContextValue({ name, value, model, onChange, parent, onDestroy }) {
    const ctx = new FormContextValue(name, [{ ...model, label: undefined, default: value }], parent);
    onDestroy.push(getFirstVariableOfContext(ctx).onChange(onChange));
    return ctx;
}
function createFormContextsFromValue({ value, ...other }) {
    return Array.isArray(value)
        ? value.map(v => createFormContextValue({ value: v, ...other }))
        : [createFormContextValue(other)];
}
export const ObjectListField = ({ name, value, onChange, variable }) => {
    const parent = useJinjaContext();
    const model = variable.config.model;
    const onDestroy = useRef([]);
    const [_, forceUpdate] = useState(Math.random());
    const handleAnyChange = useCallback(() => {
        onChange(items.current.map(ctx => getFirstVariableOfContext(ctx).get()));
    }, []);
    const items = useRef(createFormContextsFromValue({ value, name, model, parent: parent, onDestroy: onDestroy.current, onChange: handleAnyChange }));
    const rendered = useMemo(() => items.current.map((item, index) => {
        const fields = buildFields(item.variables);
        return (_jsxs(JinjaRawContext, { value: item, children: [_jsx(FieldRenderer, { Component: fields[0], input: model.metadata }), _jsx(Button, { onClick: () => removeItem(index), children: "Remover" })] }, index));
    }), [items.current]);
    function addItem() {
        items.current = ([...items.current, createFormContextValue({ name, model, onChange: handleAnyChange, onDestroy: onDestroy.current, parent: parent })]);
        forceUpdate(Math.random());
        handleAnyChange();
    }
    function removeItem(index) {
        items.current = items.current.filter((_, i) => i !== index);
        forceUpdate(Math.random());
        handleAnyChange();
    }
    return (_jsxs("div", { className: "dynamic-list", children: [rendered, _jsx(Button, { onClick: addItem, children: "Adicionar" })] }));
};
//# sourceMappingURL=ObjectListField.js.map