import { ActionFormData, MessageFormData } from '@minecraft/server-ui'
import { Player } from '@minecraft/server'

/**
 * Displays an action form with support for nested forms.
 * @param {Player} player 
 * @param {string} category 
 * @param {Array<{text: string, image?: string, subpages?: any[]}>} pages 
 * @param {() => {}} back 
 */
export function actionForm(player, category, pages, back) {
    const form = new ActionFormData()
        .title(`form.ecbl_bc.guide_book.${category}.title`)
        .body(`form.ecbl_bc.guide_book.${category}.body`);

    // Generate buttons dynamically
    pages.forEach((p) => {
        if (p?.image) {
            form.button(`form.ecbl_bc.guide_book.${category}.${p.text}`, p.image);
        } else {
            form.button(`form.ecbl_bc.guide_book.${category}.${p.text}`);
        }
    });

    if (back) {
        form.button(`form.ecbl_bc.guide_book.button.back`, 'textures/eternal/biome_craft/ui/new_back');
    }
    form.button(`form.ecbl_bc.guide_book.button.close`, 'textures/eternal/biome_craft/ui/new_quit');

    form.show(player).then((r) => {
        if (r.canceled || r.selection === pages.length + (back ? 1 : 0)) return;
        if (back && r.selection === pages.length) { back(player); return; }

        const selectedPage = pages[r.selection];

        if (selectedPage.subpages) {
            // If the selected item has subpages, open a new actionForm
            actionForm(player, `${selectedPage.text}`, selectedPage.subpages, () => {
                actionForm(player, category, pages, back);
            });
        } else {
            // Otherwise, open a messageForm
            messageForm(player, category, selectedPage.text, () => {
                actionForm(player, category, pages, back);
            });
        }
    });
}

/**
 * Displays a message form.
 * @param {Player} player 
 * @param {string} category 
 * @param {string} topic 
 * @param {() => {}} back 
 */
export function messageForm(player, category, topic, back) {
    new MessageFormData()
        .title(`form.ecbl_bc.guide_book.${category}.${topic}.title`)
        .body({ rawtext: [{ translate: `form.ecbl_bc.guide_book.${category}.${topic}.body` }] })
        .button2(`form.ecbl_bc.guide_book.button.back`)
        .button1(`form.ecbl_bc.guide_book.button.close`)
        .show(player)
        .then((r) => {
            if (r.canceled) return;
            if (r.selection === 1) {
                back(player);
            }
        });
}
