export default class DynamicFormAdapter {
    constructor({ api = null, schema = null } = {}) {
        this.formEl = null;
        this.api = api;
        this.schema = schema;
    }

    async mount(el, record = {}, schema = null) {
        const currentSchema = schema || this.schema;

        el.innerHTML = "";

        if (!currentSchema || !Array.isArray(currentSchema.fields)) {
            console.error("[DynamicFormAdapter] No valid schema fields found.");
            return;
        }

        const relationTasks = [];

        // 1) فقط ساخت DOM، بدون await
        for (const field of currentSchema.fields) {
            const key = field.field_name;
            const wrapper = document.createElement("div");
            wrapper.className = "form-group mb-3";
            wrapper.dataset.fieldName = key;

            const labelEl = document.createElement("label");
            labelEl.textContent = field.field_label || key;
            wrapper.appendChild(labelEl);

            const value = record[key] ?? "";

            const input = document.createElement("input");
            input.name = key;
            input.value = value;
            input.className = "form-control";

            if (field.field_type === "date") {
                input.type = "date";
            } else if (field.field_type === "relation") {
                input.type = "hidden";
            } else {
                input.type = "text";
            }

            wrapper.appendChild(input);
            el.appendChild(wrapper);

            // 2) async relation hints را بعداً بارگذاری کن
            if (field.field_type === "relation" && value) {
                relationTasks.push({
                    wrapper,
                    field,
                    value,
                });
            }
        }

        this.formEl = el.closest("form") || el;

        // 3) لود relationها را در پس‌زمینه انجام بده
        this._loadRelationHints(relationTasks);
    }

    async _loadRelationHints(tasks = []) {
        if (!tasks.length || !this.api) return;

        const promises = tasks.map(async ({ wrapper, field, value }) => {
            try {
                const res = await this.api.get(
                    `/runtime/${field.source_entity}/record/${value}`
                );

                const name = res?.data?.name || res?.name || "";

                if (!name) return;

                let hint = wrapper.querySelector(".relation-hint");
                if (!hint) {
                    hint = document.createElement("small");
                    hint.className = "relation-hint";
                    hint.style.display = "block";
                    hint.style.marginTop = "4px";
                    hint.style.color = "#6b7280";
                    wrapper.appendChild(hint);
                }

                hint.textContent = `نمایش: ${name}`;
            } catch (err) {
                console.warn(
                    `[DynamicFormAdapter] Failed to load relation label for ${field.field_name}:`,
                    err
                );
            }
        });

        await Promise.all(promises);
    }

    getValue() {
        if (!this.formEl) return {};

        const data = {};
        const elements = this.formEl.querySelectorAll("input, select, textarea");

        for (const el of elements) {
            if (!el.name) continue;
            data[el.name] = el.value;
        }

        return data;
    }
}
