import { UnlockOutlined } from "@ant-design/icons";
import { Tag } from "antd";
import { useCallback, useMemo, useState } from "react";

import { UpsellModal } from "../components/upsell/modal.js";
import { useI18n } from "../contexts/i18n.js";
import { useUpsell } from "../contexts/upsell.js";

import type { UpsellFeature } from "../components/upsell/modal.js";
import type { BaseSyntheticEvent } from "react";

const UPSELL_TAG_BACKGROUND_COLOR = "#2db7f5";

const ASSETS_URL = "https://assets.devowl.io/in-app/wp-real-cookie-banner/";

/**
 * Provide a PRO modal when clicking a given button.
 *
 * @param overrideIsPro Allows to override the `isPro` attribute coming from the option store (e. g. for demo environment purposes, try.devowl.io)
 */
function useUpsellModal(feature: UpsellFeature, overrideIsPro?: boolean) {
    const { __ } = useI18n();
    const { isPro, isLicensed } = useUpsell();
    const [visible, setVisible] = useState(false);
    const useIsPro = typeof overrideIsPro === "boolean" ? overrideIsPro : isPro;

    const open = useCallback(
        (e?: BaseSyntheticEvent) => {
            setVisible(true);
            e?.preventDefault();
        },
        [setVisible],
    );

    const tag = useMemo(
        () =>
            useIsPro ? null : (
                <Tag
                    icon={<UnlockOutlined />}
                    color={UPSELL_TAG_BACKGROUND_COLOR}
                    style={{ cursor: "pointer" }}
                    onClick={open}
                >
                    {feature.tagText || __("Unlock feature")}
                </Tag>
            ),
        [open, feature],
    );

    const modal = useMemo(
        () =>
            useIsPro && feature.mode !== "license-activation" ? null : (
                <UpsellModal visible={visible} onClose={() => setVisible(false)} {...feature} />
            ),
        [visible, setVisible, feature],
    );

    return { isPro: useIsPro, isLicensed, tag, modal, open };
}

export { useUpsellModal, UPSELL_TAG_BACKGROUND_COLOR, ASSETS_URL };
