/** @odoo-module **/

import {Component, useState} from "@odoo/owl";
import {useOwnedDialogs, useService} from "@web/core/utils/hooks";
import {TranslationDialog} from "@web/views/fields/translation_dialog";

/**
 * @param {Object} env - OWL environment from the component (this.env)
 * @returns {Function} openTranslationDialog
 */
export function useTranslationDialog(env) {
    const addDialog = useOwnedDialogs();

    async function openTranslationDialog({name, id}) {
        addDialog(TranslationDialog, {
            fieldName: "name",
            resId: id,
            resModel: "ir.ui.menu",
            userLanguageValue: name || "",
            isComingFromTranslationAlert: false,
            userUserCurrentLang: true,
            onSave: async () => {
                env.bus.trigger("CLEAR-CACHES");
                await env.services.action.doAction({
                    type: "ir.actions.client",
                    tag: "reload",
                });
            },
        });
    }

    return openTranslationDialog;
}

export class MenuTranslationButton extends Component {
    setup() {
        this.orm = useService("orm");
        this.state = useState({record: {}});
        this.translationDialog = useTranslationDialog(this.env);
    }

    async onClick() {
        const xmlId = this.props.menuXmlId;
        const [module, name] = xmlId.split(".");
        if (!module || !name) {
            console.error("Неверный формат menuXmlId");
            return;
        }

        try {
            const [menuIdRecord] = await this.orm.searchRead(
                "ir.model.data",
                [
                    ["model", "=", "ir.ui.menu"],
                    ["name", "=", name],
                    ["module", "=", module],
                ],
                ["res_id"]
            );

            if (!menuIdRecord) {
                console.error("Меню не найдено по XML ID");
                return;
            }

            const menuId = menuIdRecord.res_id;
            const [menuRecord] = await this.orm.searchRead("ir.ui.menu", [["id", "=", menuId]], ["id", "name", "action"]);

            if (!menuRecord) {
                console.error("Запись меню не найдена");
                return;
            }

            this.state.record = menuRecord;

            this.translationDialog({
                name: menuRecord.name,
                id: menuRecord.id,
            });
        } catch (error) {
            console.error("Ошибка при получении меню:", error);
        }
    }
}

MenuTranslationButton.template = "translation_helper.MenuTranslationButton";
MenuTranslationButton.props = {
    menuXmlId: {
        type: String,
        optional: false,
    },
};
