import { useEffect, useMemo, useState } from "@wordpress/element";
import { useSelect, useDispatch } from "@wordpress/data";
import { Toaster } from "react-hot-toast";
import Header from "./templates/Header";
import QuickStart from "./pages/quickStart/quickStart";
import BlockVisibility from "./pages/blockVisibility";
import SavedTemplates from "./pages/saved-templates";
import SettingsPage from "./pages/settings";
import Modules from "./pages/modules";
import AboutUs from "./pages/about-us";
import LiteVsPro from "./pages/lite-vs-pro";
import SetupWizard from "./setup-wizard";
import { STORE_NAME } from "./store";
import { OurPluginsIcon } from "./Icons";

// Inject Crisp chat script
const initCrispChat = () => {
	if (window.$crisp) {
		return;
	}
	const crispWebsiteId = window.sp_real_admin_dashboard_localize?.crisp_website_id;
	if (!crispWebsiteId) {
		return;
	}
	window.$crisp = [];
	window.CRISP_WEBSITE_ID = crispWebsiteId;
	(function () {
		const d = document;
		const s = d.createElement("script");
		s.src = "https://client.crisp.chat/l.js";
		s.async = 1;
		d.getElementsByTagName("head")[0].appendChild(s);
	})();
};

// Function to update the active state of sidebar menu items.
const updateSidebarActive = (pageName) => {
	const postMenu = document.getElementById("menu-posts-spt_testimonial");
	if (!postMenu) {
		return;
	}

	// Remove 'current' class from all items
	postMenu.querySelectorAll("li").forEach((el) => el.classList.remove("current"));
	// Determine selector based on pageName
	const selector =
		pageName === "getting-start" || pageName === ""
			? 'li a[href*="post_type=spt_testimonial&page=rtp_dashboard"]'
			: `li a[href*="#${pageName}"]`;
	// Add 'current' class if match found
	postMenu.querySelector(selector)?.closest("li")?.classList.add("current");
};

const Render = () => {
	const hashValue = window.location?.hash?.replace("#", "")?.split("=")[0];
	// Update Sidebar active menu based on hash link.
	updateSidebarActive(hashValue);
	const [page, setPage] = useState(hashValue ? hashValue : "getting-start");

	useEffect(() => {
		const pluginsContainer = document.querySelector(".sp-real-recommended-plugins-wrapper");
		if (hashValue === "our_plugins" && pluginsContainer) {
			pluginsContainer.style.display = "block";
		}
		const postMenu = document.getElementById("menu-posts-spt_testimonial");
		const allItems = postMenu.querySelectorAll("li");

		const removeCurrentClass = () => {
			allItems.forEach((element) => {
				element.classList.remove("current");
			});
		};

		const postMenuAction = (e) => {
			const currentItem = e.target.closest("li");
			removeCurrentClass();

			currentItem.classList.add("current");

			setTimeout(() => {
				setPage(window.location.hash.replace("#", ""));
			}, 0);
		};
		postMenu.addEventListener("click", postMenuAction);

		return () => postMenu.removeEventListener("click", postMenuAction);
	}, []);

	const setPageAndHash = (pageName) => {
		setPage(pageName);
		const pluginsContainer = document.querySelector(".sp-real-recommended-plugins-wrapper");
		if (pageName === "our_plugins" && pluginsContainer) {
			pluginsContainer.style.display = "block";
		} else if (pluginsContainer) {
			pluginsContainer.style.display = "none";
		}
		window.location.hash = pageName;
	};

	// Fetch settings data from the Redux store.
	const pluginSettings = useSelect((select) => select(STORE_NAME).getSettings());

	// fetch data.
	const { fetchApiData, fetchSavedTemplates } = useDispatch(STORE_NAME);
	useEffect(() => {
		fetchApiData();
		fetchSavedTemplates();
	}, [fetchApiData, fetchSavedTemplates]);

	// Initialize Crisp chat
	useEffect(() => {
		initCrispChat();
	}, []);

	const menuItems = useMemo(() => {
		if (!pluginSettings) {
			return [];
		}
		let items = [
			{ label: "Dashboard", value: "getting-start", hash: "#" },
			{ label: "Blocks", value: "blocks", hash: "#blocks", badge: "new" },
			{ label: "Modules", value: "modules", hash: "#modules" },
			{ label: "Saved Templates", value: "saved_templates", hash: "#saved_templates" },
			{ label: "Settings", value: "settings", hash: "#settings" },
			{ label: "Lite vs Pro", value: "lite_vs_pro", hash: "#lite_vs_pro" },
			{ label: "Our Plugins", value: "our_plugins", hash: "#our_plugins", icon: <OurPluginsIcon /> },
		];
		const isActiveTemplates = pluginSettings?.modules?.saved_templates
			? pluginSettings?.modules?.saved_templates?.is_active
			: true;
		if (!isActiveTemplates) {
			items = items?.filter((i) => i.value !== "saved_templates");
		}
		return items;
	}, [pluginSettings]);

	// if not exist plugin settings then return;
	if (Object.keys(pluginSettings || {}).length === 0) {
		return null;
	}

	if (page === "setupwizard") {
		return <SetupWizard />;
	}

	return (
		<>
			<div className="sp-real-admin-dashboard-container">
				{/* header */}
				<Header menuItems={menuItems} currentPage={page} setPageAndHash={setPageAndHash} />
				{/* Render pages based on tab click */}
				<div className="sp-real-admin-dashboard-content">
					{page === "getting-start" && <QuickStart setPageAndHash={setPageAndHash} />}
					{page === "blocks" && <BlockVisibility />}
					{page === "modules" && <Modules />}
					{page === "saved_templates" && <SavedTemplates />}
					{page === "settings" && <SettingsPage />}
					{page === "lite_vs_pro" && <LiteVsPro />}
					{page === "about_us" && <AboutUs />}
				</div>
			</div>
			{/* React Hot Toast Container for notifications */}
			<Toaster
				position="top-right"
				toastOptions={{
					style: {
						padding: "16px 24px",
						fontSize: "18px",
						borderRadius: "10px",
						maxWidth: "400px",
					},
				}}
			/>
		</>
	);
};

export default Render;
