import {__} from "@wordpress/i18n";
import React, {useEffect} from "react";
import {PluginDocumentSettingPanel, store} from "@wordpress/editor";
import {Button, CheckboxControl} from "@wordpress/components";
import {useDispatch, useSelect} from "@wordpress/data";
import {AccountObjectTypes} from "./types/account-object-types";
import {FreemiusOverlay} from "../../components/FreemiusOverlay";
import {normalizeUrl} from "../../utils/normalizeUrl";
import {external, lock} from "@wordpress/icons";
import {createRoot} from "react-dom/client";

const settings: AccountObjectTypes = (window as any).hulk_woo_ap_account_object;
const systemRoles = settings.system_roles ?? {};
const licensing = settings.licensing;

function TopBarRight() {
	const slug = useSelect(
		(select) => select(store).getEditedPostAttribute("slug"),
		[],
	);

	const status = useSelect(
		(select) => select(store).getEditedPostAttribute("status"),
		[],
	);

	const isSavingPost = useSelect(
		(select) => select(store).isSavingPost(),
		[],
	);

	if (status !== 'publish') {
		return null;
	}

	return (
		<Button
			type={"button"}
			href={normalizeUrl(`${settings.account_page_url}/${slug}`)}
			target={"_blank"}
			size={"compact"}
			title={__("View Page", "hulk-account-pages-for-woocommerce")}
			disabled={isSavingPost}
			icon={external}
		/>
	);
}

function TopBarLeft() {
	return (
		<Button
			type={"button"}
			variant={"secondary"}
			size={"compact"}
			style={{marginLeft: "20px"}}
			href={settings.add_new_page_url}
		>
			{__("Add Page", "hulk-account-pages-for-woocommerce")}
		</Button>
	);
}

const SettingsPanel = () => {
	const meta = useSelect(
		(select) => select(store).getEditedPostAttribute("meta"),
		[],
	);

	useEffect(() => {
		const topLeft = document.querySelector(".editor-header__toolbar");
		const topRight = document.querySelector(".editor-header__settings");
		if (!topLeft || !topRight) return;
		// Top bar left
		const divElementLeft = document.createElement("div");
		divElementLeft.setAttribute("id", "hulk-woo-ap-left-panel");
		if (!document.getElementById("hulk-woo-ap-left-panel")) {
			topLeft.append(divElementLeft);
		}
		// Top bar right
		const divElementRight = document.createElement("div");
		divElementRight.setAttribute("id", "hulk-woo-ap-right-panel");
		if (!document.getElementById("hulk-woo-ap-right-panel")) {
			topRight.prepend(divElementRight);
		}
		createRoot(divElementLeft!)?.render(<TopBarLeft/>);
		createRoot(divElementRight!)?.render(<TopBarRight/>);
	}, []);

	const {editPost} = useDispatch("core/editor");

	const selectedRoles = meta?.hulk_woo_ap_user_roles?.[0]
		? meta.hulk_woo_ap_user_roles // Saved roles
		: Object.keys(systemRoles); // Default: all roles

	const toggleRole = (role: string) => {
		// Check if user is a trial or have feature enabled license.
		if (!licensing?.can_use_premium_code) {
			return;
		}

		let updatedRoles;

		if (selectedRoles.includes(role)) {
			updatedRoles = selectedRoles.filter((r: string) => r !== role);
		} else {
			updatedRoles = [...selectedRoles, role];
		}

		editPost({
			meta: {hulk_woo_ap_user_roles: updatedRoles},
		});
	};

	return (
		<PluginDocumentSettingPanel
			name="hulk_woo_ap_user_roles"
			title={__(
				"Account Page Settings",
				"hulk-account-pages-for-woocommerce",
			)}
			className={"hulk_woo_ap_user_roles"}
			{...(!licensing?.can_use_premium_code && {
				icon: lock,
			})}
		>
			<p className={"components-text"}>
				{__(
					"Show this page for the following selected user roles:",
					"hulk-account-pages-for-woocommerce",
				)}
			</p>
			{licensing?.notice && (
				<p dangerouslySetInnerHTML={{__html: licensing.notice}}/>
			)}
			<FreemiusOverlay
				PLUGIN_DIR_URL={settings?.PLUGIN_DIR_URL}
				can_use_premium_code={licensing?.can_use_premium_code}
				is_premium={licensing?.is_premium}
				checkout_url={licensing?.checkout_url}
				is_not_paying={licensing?.is_not_paying}
				get_upgrade_url={licensing?.get_upgrade_url}
			>
				{Object.entries(systemRoles).map(([key, name]) => (
					<CheckboxControl
						name={"hulk_woo_ap_user_roles[]"}
						key={`hulk_woo_ap_user_role-${key}`}
						label={name}
						checked={selectedRoles.includes(key)}
						onChange={() => toggleRole(key)}
					/>
				))}
			</FreemiusOverlay>
		</PluginDocumentSettingPanel>
	);
};

export default SettingsPanel;
