import {__} from "@wordpress/i18n";
import React, {ComponentProps, useState} from "react";
import {Button, Modal} from "@wordpress/components";
import {Settings} from "../admin/settings/types/settings";

const settings = (window as any).hulk_woo_pdil_settings as Settings;
const licensing = settings.licensing;

const FreemiusOverlay = ({children}: ComponentProps<"div">) => {
	const [isOpen, setOpen] = useState(false);
	const openModal = () => setOpen(true);
	const closeModal = () => setOpen(false);

	if (!licensing.can_use_premium_code) {
		return (
			<>
				<div
					className={"freemius-overlay"}
					onClick={openModal}
					role="button"
					tabIndex={0}
					onKeyDown={(event) => {
						if (event.key === "Enter") {
							openModal();
						}
					}}
				>
					{children}
				</div>
				{isOpen && (
					<Modal
						size={"small"}
						onRequestClose={closeModal}
						className={"hulk-pro-modal"}
					>
						<ModalContent
							is_premium={licensing.is_premium}
							checkout_url={licensing.checkout_url}
							is_not_paying={licensing.is_not_paying}
							get_upgrade_url={licensing.get_upgrade_url}
							PLUGIN_DIR_URL={settings.PLUGIN_DIR_URL}
						/>
					</Modal>
				)}
			</>
		);
	}

	return children;
};

function ModalContent(
	{
		is_premium,
		checkout_url,
		is_not_paying,
		get_upgrade_url,
		PLUGIN_DIR_URL,
	}: {
		is_premium: boolean;
		checkout_url: string;
		is_not_paying: boolean;
		get_upgrade_url: string;
		PLUGIN_DIR_URL: string;
	}
) {
	return (
		<div className="hulk-modal-wrap">
			<div className="hulk-modal-icon">
				<img
					src={`${PLUGIN_DIR_URL}/assets/icons/modal-icon.svg`}
					alt={__("Upgrade", "product-description-in-loop-for-woocommerce")}
					loading="lazy"
				/>
			</div>
			{!is_premium ? (
				<>
					<h4>
						{__(
							"To use",
							"product-description-in-loop-for-woocommerce",
						)}
					</h4>
					<Button
						type={"button"}
						variant={"primary"}
						href={checkout_url}
						target={"_blank"}
					>
						{__(
							"UNLOCK PRO",
							"product-description-in-loop-for-woocommerce",
						)}
					</Button>
				</>
			) : (is_not_paying && (
				<>
					<h4>
						{__(
							"To use",
							"product-description-in-loop-for-woocommerce",
						)}
					</h4>
					<Button
						type={"button"}
						variant={"primary"}
						href={get_upgrade_url}
						target={"_blank"}
					>
						{__(
							"UPGRADE NOW!",
							"product-description-in-loop-for-woocommerce",
						)}
					</Button>
				</>
			))}
		</div>
	);
}

export {FreemiusOverlay, ModalContent};
