import { openLocation } from "/modules/augur-nexus/scripts/api/locations.js";
import { TradeGoodRegionModel } from "../models/TradeGoodRegionModel.js";
import { TradeRegionSceneService } from "../services/TradeRegionSceneService.js";

const { ApplicationV2, HandlebarsApplicationMixin } = foundry.applications.api;

export class TradeGoodDetailApplication extends HandlebarsApplicationMixin(ApplicationV2) {
    #goodId = "";
    #locationId = "";
    #sceneId = "";
    #model = null;
    #hooks = [];

    static DEFAULT_OPTIONS = {
        id: "augur-nexus-trade-good-detail",
        classes: ["augur-nexus", "augur-theme-fantasy", "trade-good-detail"],
        tag: "div",
        window: { title: "Trade Good", resizable: true, minimizable: true },
        position: { width: 820, height: 620 },
        actions: {
            openTradeGoodLocation: TradeGoodDetailApplication._onOpenLocation
        }
    };

    static PARTS = { content: { template: "modules/augur-nexus/templates/trade/trade-good-detail.hbs" } };

    static async show({ goodId = "", locationId = "", sceneId = "" } = {}) {
        if (!goodId || !locationId) return null;
        const resolvedSceneId = await TradeRegionSceneService.chooseSceneId(locationId, { sceneId });
        const app = new this({ goodId, locationId, sceneId: resolvedSceneId });
        app.render(true, { focus: true });
        return app;
    }

    constructor({ goodId = "", locationId = "", sceneId = "" } = {}, options = {}) {
        super(options);
        this.#goodId = String(goodId || "");
        this.#locationId = String(locationId || "");
        this.#sceneId = String(sceneId || "");
        const refresh = () => this.#refresh();
        for (const hook of ["augurNexusConnectionsChanged", "augurNexusCampaignEntitiesChanged", "augurNexusShopsChanged", "augurNexusTradeGoodsChanged", "createTile", "updateTile", "deleteTile"]) {
            Hooks.on(hook, refresh);
            this.#hooks.push([hook, refresh]);
        }
    }

    get title() { return this.#model?.good?.name ? `${this.#model.good.name} Trade` : "Trade Good"; }

    async _prepareContext() {
        this.#model = await TradeGoodRegionModel.build({
            goodId: this.#goodId,
            locationId: this.#locationId,
            sceneId: this.#sceneId,
            user: game.user
        });
        this.#sceneId = this.#model?.sceneId || "";
        return { missing: !this.#model, ...(this.#model || {}) };
    }

    _onRender(context, options) {
        super._onRender(context, options);
        if (this.window?.title) this.window.title.textContent = this.title;
    }

    async close(options) {
        for (const [hook, callback] of this.#hooks) Hooks.off(hook, callback);
        this.#hooks = [];
        return super.close(options);
    }

    static _onOpenLocation(_event, target) {
        const locationId = String(target?.dataset?.locationId || "");
        if (locationId) return openLocation(locationId);
    }

    #refresh() {
        if (this.rendered !== false) this.render({ parts: ["content"] });
    }
}
