import { UnlockFilled } from "@ant-design/icons";
import { Modal } from "antd";
import { useCallback, useEffect, useState } from "react";

import { reactNl2Br } from "@devowl-wp/react-utils";

import {
    IN_APP_FOMO_URL_PARAMETER_TO_DEACTIVATE_WEBSITE_FOMO,
    UpsellInAppFomoCouponCounter,
} from "./inAppFomoCouponCounter.js";
import { UpsellModalHint } from "./modalHint.js";
import { useI18n } from "../../contexts/i18n.js";
import { useUpsell } from "../../contexts/upsell.js";

import type { FC, ReactNode } from "react";

type UpsellFeature = {
    title: string;
    mode?: "license-activation" | "pro";
    testDrive?: boolean;
    assetName?: string;
    assetMaxHeight?: number;
    description: string | ReactNode;
    feature: string;
    tagText?: string;
};

const UpsellModal: FC<
    UpsellFeature & {
        visible?: boolean;
        /**
         * Show hints generated through `RCB/Hints`.
         */
        showHints?: boolean;
        showFomoCouponCounter?: boolean;
        onClose?: () => void;
        /**
         * Puts the modal in an always-visible state inside a given selector.
         * Use it together with the `.rcb-antd-modal-mount` CSS class.
         *
         * @see https://stackoverflow.com/a/58399650/5506547
         */
        inContainer?: boolean;
        inContainerElement?: HTMLElement;
    }
> = ({
    mode = "pro",
    visible = false,
    showHints = true,
    showFomoCouponCounter = true,
    title,
    testDrive = false,
    assetName,
    assetMaxHeight,
    description,
    feature,
    onClose,
    inContainer,
    inContainerElement,
}) => {
    const { __, _i } = useI18n();
    const { proUrl, hint, isPro } = useUpsell();
    const [descriptionRef, setDescriptionRef] = useState<HTMLElement>();
    const handleRedirect = useCallback(() => {
        if (mode === "pro") {
            window
                .open(`${proUrl}&feature=${feature}&${IN_APP_FOMO_URL_PARAMETER_TO_DEACTIVATE_WEBSITE_FOMO}`, "_blank")
                .focus();
        } else {
            window.location.href = `#/licensing?navigateAfterActivation=${encodeURIComponent(window.location.href)}`;
        }
        onClose?.();
    }, [onClose, mode]);

    // Do not automatically scroll / focus the container if `inContainer` is set
    useEffect(() => {
        if (inContainer && descriptionRef) {
            (descriptionRef.parentElement.parentElement.parentElement as HTMLDivElement).removeAttribute("tabIndex");
        }
    }, [descriptionRef]);

    // Do not output the model until the container is ready
    if (inContainer && !inContainerElement) {
        return null;
    }

    const assetSrc = assetName ? `https://assets.devowl.io/in-app/wp-real-cookie-banner/${assetName}` : undefined;

    return (
        <Modal
            transitionName={inContainer ? null : undefined}
            open={inContainer ? true : visible}
            title={
                <span>
                    <UnlockFilled />
                    &nbsp;
                    {title}
                    &nbsp;
                    {mode === "pro" && __("Get PRO!")}
                </span>
            }
            onOk={handleRedirect}
            onCancel={onClose}
            cancelText={__("No, not interested...")}
            okText={
                mode === "pro"
                    ? __("I want to learn more!")
                    : isPro
                      ? __("Activate license")
                      : __("Activate free license")
            }
            className="rcb-antd-hero-modal"
            width={assetName ? 800 : 700}
            getContainer={inContainer ? inContainerElement : undefined}
        >
            {!!assetName &&
                (assetName.endsWith(".webm") ? (
                    <video autoPlay muted loop style={{ marginTop: 10, maxHeight: assetMaxHeight }}>
                        <source src={assetSrc} type="video/webm" />
                    </video>
                ) : (
                    <img style={{ marginTop: 10, maxHeight: assetMaxHeight }} src={assetSrc} />
                ))}
            <div style={{ maxWidth: 600, margin: "auto" }} ref={setDescriptionRef}>
                <p>{typeof description === "string" ? reactNl2Br(description) : description}</p>
                {testDrive && mode === "pro" && (
                    <p>
                        {_i(__("Check out this feature with a {{a}}free sandbox{{/a}} before buying!"), {
                            a: <a href={__("https://try.devowl.io/?product=RCB")} target="_blank" rel="noreferrer" />,
                        })}
                    </p>
                )}
            </div>
            {!!hint && showHints && mode === "pro" && (
                <div style={{ maxWidth: 600, margin: "auto", textAlign: "left" }}>
                    <UpsellModalHint {...hint} />
                </div>
            )}
            {showFomoCouponCounter && mode === "pro" && <UpsellInAppFomoCouponCounter style={{ marginBottom: 15 }} />}
        </Modal>
    );
};

export { type UpsellFeature, UpsellModal };
