class SliderConfigurator extends Application {
    constructor(id) {
        super();
        this.data = game.settings.get("progress-tracker", "sliders")[id];
    }

    static get defaultOptions() {
        return {
            ...super.defaultOptions,
            title: "Sliders Configurator",
            id: "sliders-configurator",
            template: `modules/progress-tracker/templates/sliders-configurator.hbs`,
            resizable: true,
            width: 300,
            height: window.innerHeight > 400 ? 400 : window.innerHeight - 100,
            dragDrop: [{ dragSelector: null, dropSelector: null }],
        };
    }

    getData() {
        return {};
    }

    activateListeners(html) {
        html.find(".progress-container").append(this.generateContent(this.data));
        html.on("click", ".add-slider", () => {
            const slider = this.addSlider();
            html.find(".sliders-container").append(slider);
        });
        html.on("click", ".add-waypoint", () => {
            const waypoint = this.addWaypoint();
            html.find(".waypoints-container").append(waypoint);
        });
        html.on("click", ".save-progress", this.saveData.bind(this));
        html.on("click", "#deleteItem", (e) => {
            $(e.currentTarget).closest(".waypoint-container").remove();
            $(e.currentTarget).closest(".slider-container").remove();
        });
        html.on("click", "#pick-file", this._activateFilePicker.bind(this));
    }

    _activateFilePicker(event) {
        event.preventDefault();
        const options = this._getFilePickerOptions(event);
        const fp = new FilePicker(options);
        return fp.browse();
    }

    _getFilePickerOptions(event) {
        const button = event.currentTarget;
        const field = $(button).closest(".form-fields").find("input") || null;
        return {
            field: field[0],
            type: button.dataset.type,
            current: field.val() || null,
            button: button,
        };
    }

    generateContent(data) {
        let sliders = `<div class="sliders-container">`;
        let waypoints = `<div class="waypoints-container">`;
        for (let slider of data.sliders) {
            sliders += `<div class="slider-container">`;
            sliders += this.filepickerImageComponent({
                label: "Slider",
                value: slider.img,
            });
            sliders += `
      <div class="form-group">
          <label>Name: </label>
          <div class="form-fields">
              
              <input type="text" id="name" value="${slider.name || ""}" placeholder="name" class="">
  
          </div>
      </div>`;
            sliders += `</div>`;
        }
        for (let waypoint of data.waypoints) {
            waypoints += `<div class="waypoint-container">`;
            waypoints += this.filepickerImageComponent({
                label: "Waypoint",
                value: waypoint.img,
            });
            waypoints += `
            <div class="form-group">
                <label>Percentage: </label>
                <div class="form-fields">
                    
                    <input type="number" id="percentage" value="${waypoint.percent || 0}" placeholder="0" class="" step="1">
        
                </div>
            </div>`;
            waypoints += `</div>`;
        }
        sliders += `</div>
        <button class="add-slider">Add Slider</button>
        <hr>
        `;
        waypoints += `</div>
        <button class="add-waypoint">Add Waypoint</button>
        <hr>
        `;
        const $li = `
        <div class="form-group">
        <label>Name: </label>
        <div class="form-fields">
            
            <input type="text" value="${data.name || ""}" placeholder="name" class="">

        </div>
        </div>
            ${this.filepickerImageComponent({
                label: "Background",
                value: data.bg,
            })}
            <hr>
            ${sliders}
            ${waypoints}
        `;
        return $li;
    }

    addSlider() {
        let slider = "";
        slider += `<div class="slider-container">`;
        slider += this.filepickerImageComponent({
            label: "Slider",
            value: "",
        });
        slider += `
    <div class="form-group">
        <label>Name: </label>
        <div class="form-fields">
            
            <input type="text" id="name" value="" placeholder="name" class="">

        </div>
    </div>`;
        slider += `</div>`;
        return $(slider);
    }

    addWaypoint() {
        let waypoint = "";
        waypoint += `<div class="waypoint-container">`;
        waypoint += this.filepickerImageComponent({ label: "Waypoint", value: "" });
        waypoint += `
        <div class="form-group">
            <label>Percentage: </label>
            <div class="form-fields">
                
                <input type="number" value="" id="percentage" placeholder="0" class="" step="1">
    
            </div>
        </div>`;
        waypoint += `</div>`;
        return $(waypoint);
    }

    filepickerImageComponent(data) {
        const $filepickerImageComponent = `
        <div class="form-group">
            <label>${data.label}</label>
            <div class="form-fields">
            <button type="button" class="file-picker" id="pick-file" data-type="imagevideo" data-target="img" title="Browse Files" tabindex="-1">
                <i class="fas fa-file-import fa-fw"></i>
            </button>
            <button type="button" class="file-picker" id="deleteItem">
            <i class="fas fa-trash"></i>
            </button>
            <input class="image" type="text" name="img" placeholder="path/image.png" value="${data.value || ""}">
            </div>
        </div>
        `;
        return $filepickerImageComponent;
    }

    saveData() {
        const settings = game.settings.get("progress-tracker", "sliders");
        const html = $(this.element);
        const bg = html.find(".image").first().val();
        const name = html.find(".form-group").first().find(".form-fields").first().find("input").first().val();
        let waypoints = [];
        html.find(".waypoint-container").each((index, waypoint) => {
            const $waypoint = $(waypoint);
            const percentage = parseInt($waypoint.find("#percentage").val()) || 0;
            waypoints.push({
                img: $waypoint.find(".image").first().val(),
                percent: percentage,
            });
        });
        let sliders = [];
        html.find(".slider-container").each((index, slider) => {
            const $slider = $(slider);
            const img = $slider.find(".image").first().val();
            const name = $slider.find("#name").val();
            sliders.push({
                img: img,
                name: name,
            });
        });
        const data = {
            id: this.data.id,
            bg: bg,
            name: name,
            sliders: sliders,
            waypoints: waypoints,
        };
        settings[this.data.id] = data;
        console.log(data);
        game.settings.set("progress-tracker", "sliders", settings);
        this.close();
    }
}

class ProgressBarsConfigurator extends Application {
    constructor(data) {
        super();
        this.data = data;
    }

    static get defaultOptions() {
        return {
            ...super.defaultOptions,
            title: "Configure Sliders",
            id: "configure-sliders",
            template: `modules/progress-tracker/templates/configure-sliders.hbs`,
            resizable: true,
            width: 300,
            height: window.innerHeight > 400 ? 400 : window.innerHeight - 100,
            dragDrop: [{ dragSelector: null, dropSelector: null }],
        };
    }

    getData() {
        return {};
    }

    activateListeners(html) {
        const _this = this;
        const settings = game.settings.get("progress-tracker", "sliders");
        for (let [k, v] of Object.entries(settings)) {
            html.find(".sliders").append(this.generateLi(v));
        }
        html.on("click", ".add-slider", this.addSlider.bind(this));
        html.on("click", ".fa-trash", async (e) => {
            Dialog.confirm({
                title: "Progress Tracker - Confirm Delete",
                content: "Are you sure you want to delete this progress tracker?",
                yes: async () => {
                    const id = $(e.currentTarget).closest(".slider").attr("id");
                    const settings = game.settings.get("progress-tracker", "sliders");
                    delete settings[id];
                    await game.settings.set("progress-tracker", "sliders", settings);
                    _this.render(true);
                },
                no: () => {},
                defaultYes: false,
            });
        });
        html.on("click", ".fa-edit", (e) => {
            const id = $(e.currentTarget).closest(".slider").attr("id");
            new SliderConfigurator(id).render(true);
        });
        html.on("click", ".fa-eye", async (e) => {
            const id = $(e.currentTarget).closest(".slider").attr("id");
            await canvas.scene.unsetFlag("progress-tracker", "progressId");
            canvas.scene.setFlag("progress-tracker", "progressId", id);
        });
    }

    generateLi(data) {
        return $(`
        <li class="slider" id="${data.id}" style="display:flex">
            <label>${data.name}</label>
            <i class="fas fa-eye" style="margin-left:auto"></i>
            <i class="fas fa-edit"></i>
            <i class="fas fa-trash"></i>
        </li>
        `);
    }

    async addSlider() {
        const settings = game.settings.get("progress-tracker", "sliders");
        const rndId = foundry.utils.randomID(20);
        settings[rndId] = { id: rndId, name: "", bg: "", sliders: [], waypoints: [] };
        await game.settings.set("progress-tracker", "sliders", settings);
        new SliderConfigurator(rndId).render(true);
        this.close();
    }

    saveData() {
        const settings = game.settings.get("progress-tracker", "sliders");
        game.settings.set("progress-tracker", "sliders", settings);
    }
}
