import $ from "jquery";

import { __ } from "../utils/i18n.js";
import { getStaticOptions } from "../utils/options.js";
import { request } from "../utils/request.js";
import { locationRestCrossDismissDelete } from "../wp-api/cross-dismiss.delete.js";

import type {
    ParamsRestCrossDismissDelete,
    RequestRestCrossDismissDelete,
    ResponseRestCrossDismissDelete,
} from "../wp-api/cross-dismiss.delete.js";

const DATA_MEMORIZE_CREATED = "crossSellingPointer";

class CrossSellingPointer {
    public readonly slug: string;

    public readonly action: string;

    public readonly position?: string;

    public readonly $handler: JQuery<HTMLElement> & {
        pointer?: (...args: any[]) => CrossSellingPointer["$handler"];
    };

    public constructor($handler: CrossSellingPointer["$handler"], slug: string, action: string, position?: string) {
        this.slug = slug;
        this.action = action;
        this.position = position;
        this.$handler = $handler;

        this.init();
    }

    public static waitForVisibleElement(selector: string, slug: string, action: string, position?: string) {
        if (!this.isActionAvailable(slug, action)) {
            return false;
        }

        const $details = $(selector);

        if ($details.length && !$details.data(DATA_MEMORIZE_CREATED)) {
            $details.data(DATA_MEMORIZE_CREATED, true);
            new CrossSellingPointer($details, slug, action, position);
        }

        return $details.length > 0;
    }

    public static isActionAvailable(slug: string, action: string) {
        return !!getStaticOptions().cross?.[slug]?.[action];
    }

    public close(e: JQuery.ClickEvent, redirect: boolean) {
        e.preventDefault();
        const force = this.$handler.pointer("widget").find('input[type="checkbox"]').is(":checked");
        this.$handler.pointer("close");
        this.$handler.pointer("destroy");

        // force means in this context, that we clicked "Rate now"
        if (redirect) {
            const { link } = this.getAction();
            window.open(link, "_blank");
        }

        request<RequestRestCrossDismissDelete, ParamsRestCrossDismissDelete, ResponseRestCrossDismissDelete>({
            location: locationRestCrossDismissDelete,
            params: {
                slug: this.slug,
                action: this.action,
                force,
            },
        });
    }

    public buttons() {
        const close = $(`<a class="button" href="#">${__("Not now")}</a>`).click((e) => {
            this.close(e, false);
        });
        const rateNow = $(`<a class="button button-primary" href="#">${__("Learn more!")}</a>`).click((e) => {
            this.close(e, true);
        });

        return $('<div class="real-utils-pointer-buttons" />').append(rateNow, close);
    }

    public getAction() {
        return getStaticOptions().cross?.[this.slug][this.action];
    }

    private init() {
        const { position } = this;
        const { title, description, image } = this.getAction();

        const neverAgainCheckbox = `<label><input type="checkbox" /> ${__("Never show this popup again")}</label>`;

        this.$handler
            .pointer({
                pointerClass: `wp-pointer real-utils-cross-pointer`,
                content: `<h3>${title}</h3><p><img src="${image}" />${description}${neverAgainCheckbox}</p>`,
                buttons: this.buttons.bind(this),
                position,
            })
            .pointer("open")
            // Reposition when image is loaded completely
            .pointer("widget")
            .find("img")
            .get(0).onload = () => this.$handler.pointer("reposition");
    }
}

export { CrossSellingPointer };
