import $ from "jquery";

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

import type {
    ParamsRestRatingDismissDelete,
    RequestRestRatingDismissDelete,
    ResponseRestRatingDismissDelete,
} from "../wp-api/rating-dismiss.delete.js";

class RatingPointer {
    public readonly slug: string;

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

    public readonly description?: string;

    public readonly className?: string;

    public constructor(slug: string, $handler: RatingPointer["$handler"], description?: string, className?: string) {
        this.slug = slug;
        this.$handler = $handler;
        this.description = description;
        this.className = className;

        this.init();
    }

    public close(e: JQuery.ClickEvent, force: boolean) {
        e.preventDefault();
        this.$handler.pointer("close");
        this.$handler.pointer("destroy");

        // force means in this context, that we clicked "Rate now"
        if (force) {
            const rateLink = getStaticOptions().rateLinks[this.slug];
            window.open(rateLink, "_blank");
        }

        request<RequestRestRatingDismissDelete, ParamsRestRatingDismissDelete, ResponseRestRatingDismissDelete>({
            location: locationRestRatingDismissDelete,
            params: {
                slug: this.slug,
                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="#">${__("Give it a rating")}</a>`).click((e) => {
            this.close(e, true);
        });

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

    private init() {
        // Reset local variable, we do not have a store
        const { canBeRated } = getStaticOptions();
        canBeRated.splice(canBeRated.indexOf(this.slug), 1);

        const headline = __("Do us a favor!");
        const desc =
            this.description ||
            __(
                "Awesome, you have just used a functionality of <strong>%s</strong>. Do you like it? Please do us a favor and rate us!",
                getStaticOptions().names[this.slug],
            );

        this.$handler
            .pointer({
                pointerClass: `wp-pointer real-utils-rate-pointer ${this.className ? this.className : ""}`,
                content: `<h3>${headline}</h3><p>${desc}</p>`,
                buttons: this.buttons.bind(this),
            })
            .pointer("open");
    }
}

export { RatingPointer };
