/** @odoo-module */

import {Dropdown} from "@web/core/dropdown/dropdown";
import {DropdownItem} from "@web/core/dropdown/dropdown_item";
import {FormLabel} from "@web/views/form/form_label";
import {TranslationDialog} from "@web/views/fields/translation_dialog";
import {patch} from "@web/core/utils/patch";
import {browser} from "@web/core/browser/browser";

patch(FormLabel, {
    components: {
        ...FormLabel.components,
        Dropdown,
        DropdownItem,
    },
});

patch(FormLabel.prototype, {
    setup() {
        super.setup(...arguments);
        this.hasTranslation = this.getHasTranslation();
    },
    getHasTranslation() {
        return Boolean(odoo.translate);
    },

    async onClickTranslate(attributeName) {
        const modelId = await this.env.services.orm.searchRead("ir.model", [["model", "=", this.props.record.resModel]], ["id"]);
        const fieldRecordId = await this.env.services.orm.searchRead(
            "ir.model.fields",
            [
                ["model_id", "=", modelId[0].id],
                ["name", "=", this.props.fieldName],
            ],
            ["id"]
        );

        this.env.services.dialog.add(TranslationDialog, {
            fieldName: attributeName,
            resId: fieldRecordId[0].id,
            resModel: "ir.model.fields",
            userLanguageValue: "",
            userUserCurrentLang: true,
            isComingFromTranslationAlert: false,
            onSave: async () => {
                this.env.bus.trigger("CLEAR-CACHES");
                // Full page reload — preserves current URL including ?translate=1
                browser.location.reload();
            },
        });
    },
});

FormLabel.template = "translation_link_generation.FormLabel";
