import { CustomImageFolderBrowser } from "../../shared/services/CustomImageFolderBrowser.js";
import { ShopIconCatalogRegistry } from "../services/ShopIconCatalogRegistry.js";

const { ApplicationV2, HandlebarsApplicationMixin } = foundry.applications.api;
const FilePicker = foundry.applications.apps.FilePicker.implementation;
const MODULE_ID = "augur-nexus";
const IMAGE_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif"];

export class ShopIconPicker extends HandlebarsApplicationMixin(ApplicationV2) {
    #onSelect = null;
    #currentCustomFolderPath = "";
    #defaultIcon = null;

    static DEFAULT_OPTIONS = {
        id: "augur-nexus-shop-icon-picker",
        classes: ["augur-nexus", "shop-icon-picker-dialog", "site-icon-picker-dialog"],
        tag: "div",
        window: { title: "Select Shop Icon", resizable: true, minimizable: false },
        position: { width: 860, height: 620 },
        actions: {
            selectSource: ShopIconPicker._onSelectSource,
            selectIcon: ShopIconPicker._onSelectIcon,
            chooseFile: ShopIconPicker._onChooseFile,
            chooseFolder: ShopIconPicker._onChooseFolder,
            clearFolder: ShopIconPicker._onClearFolder,
            folderUp: ShopIconPicker._onFolderUp,
            openFolder: ShopIconPicker._onOpenFolder
        }
    };

    static PARTS = { main: { template: "modules/augur-nexus/templates/features/shops/shop-icon-picker.hbs" } };

    constructor({ currentImageSrc = "", defaultIcon = null, onSelect = null } = {}, options = {}) {
        super(options);
        this.currentImageSrc = String(currentImageSrc || "");
        this.currentTab = options.currentTab || "built-in";
        this.#defaultIcon = defaultIcon?.imageSrc ? defaultIcon : null;
        this.#onSelect = onSelect;
    }

    async _prepareContext() {
        const customFolder = this.#getCustomFolderSetting();
        const [icons, customBrowser] = await Promise.all([ShopIconCatalogRegistry.getIcons(), this.#getCustomFolderBrowser(customFolder)]);
        return {
            icons,
            defaultIcon: this.#defaultIcon,
            currentImageSrc: this.currentImageSrc,
            currentTab: this.currentTab,
            pickerLabel: this.currentTab === "custom" ? "Custom" : "Built-In",
            customFolderPath: customFolder.path || "",
            currentCustomFolderPathLabel: customBrowser.currentPathLabel || customFolder.path || "",
            customFolderCanGoUp: customBrowser.canGoUp,
            customFolderParentPath: customBrowser.parentPath,
            customFolders: customBrowser.folders,
            hasCustomFolder: !!customFolder.path,
            customIcons: customBrowser.images
        };
    }

    static _onSelectSource(_event, target) {
        const next = String(target.dataset.source || "");
        if (!next || next === this.currentTab) return;
        this.currentTab = next;
        this.render({ parts: ["main"] });
    }

    static _onSelectIcon(_event, target) {
        const src = String(target.dataset.iconSrc || "");
        if (!src) return;
        this.#onSelect?.({
            src,
            id: String(target.dataset.iconId || "custom"),
            mode: String(target.dataset.iconMode || "catalog")
        });
        this.close();
    }

    static _onChooseFile() { this.#openFilePicker(); }
    static _onChooseFolder() { this.#openFolderPicker(); }
    static async _onClearFolder() {
        await game.settings.set(MODULE_ID, "shopCustomImageFolder", { source: "data", path: "" });
        this.#currentCustomFolderPath = "";
        this.render({ parts: ["main"] });
    }
    static _onFolderUp(_event, target) { this.#navigateCustomFolder(target.dataset.folderPath || ""); }
    static _onOpenFolder(_event, target) { this.#navigateCustomFolder(target.dataset.folderPath || ""); }

    #openFolderPicker() {
        const current = this.#getCustomFolderSetting();
        new FilePicker({
            type: "folder",
            current: current.path || "",
            activeSource: current.source || "data",
            callback: async (path, picker) => {
                await game.settings.set(MODULE_ID, "shopCustomImageFolder", {
                    source: picker.activeSource || current.source || "data",
                    path: path || ""
                });
                this.#currentCustomFolderPath = path || "";
                this.currentTab = "custom";
                this.render({ parts: ["main"] });
            },
            top: (this.position?.top ?? 100) + 40,
            left: (this.position?.left ?? 100) + 10
        }).render({ force: true });
    }

    #openFilePicker() {
        new FilePicker({
            type: "image",
            callback: path => {
                if (!path) return;
                this.#onSelect?.({ src: path, id: "custom", mode: "custom" });
                this.close();
            },
            top: (this.position?.top ?? 100) + 40,
            left: (this.position?.left ?? 100) + 10
        }).render({ force: true });
    }

    #getCustomFolderSetting() {
        const stored = game.settings.get(MODULE_ID, "shopCustomImageFolder") || {};
        return { source: stored.source || "data", path: stored.path || "" };
    }

    async #getCustomFolderBrowser(folder) {
        if (!folder?.path) return CustomImageFolderBrowser.browse();
        if (!CustomImageFolderBrowser.isWithinRoot(this.#currentCustomFolderPath, folder.path)) this.#currentCustomFolderPath = folder.path;
        return CustomImageFolderBrowser.browse({
            source: folder.source || "data",
            rootPath: folder.path,
            currentPath: this.#currentCustomFolderPath,
            extensions: IMAGE_EXTENSIONS
        });
    }

    #navigateCustomFolder(path = "") {
        const folder = this.#getCustomFolderSetting();
        const next = CustomImageFolderBrowser.normalizePath(path);
        if (!CustomImageFolderBrowser.isWithinRoot(next, folder.path)) return;
        this.#currentCustomFolderPath = next;
        this.render({ parts: ["main"] });
    }
}
