import React, { useEffect, useRef } from "react";
import { Rule, TinyMCEEditor } from "../../../types";
import { __ } from "@wordpress/i18n";
import { getContentGateData, isProAccess } from "../../../utils/localized-data";

type Props = {
	rule: Rule;
	message: string;
	onMessageChange: (message: string) => void;
	onUseGlobalMessageChange: (useGlobal: boolean) => void;
	useGlobalMessage: boolean;
};

const MessageAction = ({
	rule,
	message,
	onMessageChange,
	useGlobalMessage,
	onUseGlobalMessageChange,
}: Props) => {
	const editorRef = useRef(null);
	const editorId = `contentgate-action-message-editor-${rule.id}`;
	const isMountedRef = useRef(true);
	const editorInitializedRef = useRef(false);
	const editorInitializingRef = useRef(false);
	const onMessageChangeRef = useRef(onMessageChange);
	const prevUseGlobalMessageRef = useRef(useGlobalMessage);
	const initTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
	const savedContentRef = useRef<string | null>(null);

	useEffect(() => {
		onMessageChangeRef.current = onMessageChange;
	}, [onMessageChange]);

	// Determine if we should show global/custom message option
	const shouldShowGlobalMessageOption = isProAccess();

	useEffect(() => {
		const wasUsingGlobal = prevUseGlobalMessageRef.current;

		if (
			shouldShowGlobalMessageOption &&
			useGlobalMessage &&
			!wasUsingGlobal
		) {
			const cleanupEditor = () => {
				if (
					typeof window.wp !== "undefined" &&
					window.wp?.editor &&
					window.tinymce
				) {
					const tinymceEditor = window.tinymce.get(editorId);
					if (tinymceEditor) {
						try {
							const currentContent = tinymceEditor.getContent();
							savedContentRef.current = currentContent;
							if (onMessageChangeRef.current) {
								onMessageChangeRef.current(currentContent);
							}
							window.wp.editor.remove(editorId);
							editorInitializedRef.current = false;
						} catch (error) {}
					}
				}
			};
			cleanupEditor();
		}
	}, [shouldShowGlobalMessageOption, useGlobalMessage, editorId]);

	useEffect(() => {
		if (shouldShowGlobalMessageOption && useGlobalMessage) {
			prevUseGlobalMessageRef.current = useGlobalMessage;
			return;
		}

		const wasUsingGlobal = prevUseGlobalMessageRef.current;
		const switchingToCustom =
			shouldShowGlobalMessageOption &&
			!useGlobalMessage &&
			wasUsingGlobal;

		if (editorInitializedRef.current && !switchingToCustom) {
			prevUseGlobalMessageRef.current = useGlobalMessage;
			return;
		}

		if (switchingToCustom) {
			editorInitializedRef.current = false;
			editorInitializingRef.current = false;
		}

		isMountedRef.current = true;

		let contentToUse = message;
		if (switchingToCustom && (!message || message === "")) {
			if (savedContentRef.current) {
				contentToUse = savedContentRef.current;
			} else {
				const defaultMessage = getContentGateData(
					"restriction_global_message",
					"",
				);
				if (defaultMessage) {
					contentToUse = defaultMessage;
					if (onMessageChangeRef.current) {
						onMessageChangeRef.current(defaultMessage);
					}
				}
			}
		}

		if (typeof contentToUse === "undefined" || contentToUse === null) {
			return;
		}

		const initEditor = () => {
			const editorElement = document.getElementById(
				editorId,
			) as HTMLTextAreaElement | null;

			if (
				!isMountedRef.current ||
				typeof window.wp === "undefined" ||
				!window.wp?.editor ||
				!editorElement
			) {
				return;
			}

			if (editorInitializingRef.current) {
				return;
			}

			if (
				switchingToCustom &&
				window.tinymce &&
				window.tinymce.get(editorId)
			) {
				try {
					window.wp.editor.remove(editorId);
					editorInitializedRef.current = false;
					editorInitializingRef.current = false;
				} catch (error) {}
			}

			if (window.tinymce && window.tinymce.get(editorId)) {
				editorInitializedRef.current = true;
				editorInitializingRef.current = false;
				return;
			}

			if (editorInitializedRef.current && !switchingToCustom) {
				editorInitializingRef.current = false;
				return;
			}

			editorInitializingRef.current = true;
			if (initTimerRef.current) {
				clearTimeout(initTimerRef.current);
				initTimerRef.current = null;
			}

			if (editorElement && contentToUse) {
				editorElement.value = contentToUse;
				if (
					switchingToCustom &&
					savedContentRef.current &&
					onMessageChangeRef.current
				) {
					onMessageChangeRef.current(savedContentRef.current);
				}
			}

			try {
				window.wp.editor.initialize(editorId, {
					quicktags: false,
					mediaButtons: true,
					tinymce: {
						toolbar1:
							"undo,redo,formatselect,fontselect,fontsizeselect,bold,italic,forecolor,alignleft,aligncenter,alignright,alignjustify,bullist,numlist,outdent,indent,removeformat",
						statusbar: false,
						plugins:
							"wordpress,wpautoresize,wplink,wpdialogs,wptextpattern,wpview,colorpicker,textcolor,hr,charmap,link,fullscreen,lists",
						min_height: 200,
						autoresize_min_height: 200,
						theme_advanced_buttons1:
							"bold,italic,strikethrough,separator,bullist,numlist,separator,blockquote,separator,justifyleft,justifycenter,justifyright,separator,link,unlink,separator,undo,redo,separator",
						theme_advanced_buttons2: "",
						setup: (editor: TinyMCEEditor) => {
							if (contentToUse && editor) {
								editor.on("init", () => {
									if (
										contentToUse &&
										editor.getContent() !== contentToUse
									) {
										editor.setContent(contentToUse);
									}
								});
							}
						},
						init_instance_callback: (editor: TinyMCEEditor) => {
							editorInitializedRef.current = true;
							editorInitializingRef.current = false;
							prevUseGlobalMessageRef.current = useGlobalMessage;
							if (isMountedRef.current) {
								if (
									contentToUse &&
									editor.getContent() !== contentToUse
								) {
									editor.setContent(contentToUse);
								}

								setTimeout(() => {
									editor.on("change keyup", () => {
										if (isMountedRef.current) {
											const content =
												window.wp?.editor?.getContent(
													editorId,
												) || "";
											if (onMessageChangeRef.current) {
												onMessageChangeRef.current(
													content,
												);
											}
										}
									});
								}, 150);
							}
						},
					},
				});
			} catch (error) {
				editorInitializingRef.current = false;
			}
		};

		const attemptInit = (attempt = 0) => {
			if (editorInitializedRef.current && !switchingToCustom) {
				if (window.tinymce && window.tinymce.get(editorId)) {
					return;
				}
			}

			const editorElement = document.getElementById(editorId);
			if (
				!editorElement ||
				typeof window.wp === "undefined" ||
				!window.wp?.editor
			) {
				if (attempt < 3) {
					initTimerRef.current = setTimeout(
						() => attemptInit(attempt + 1),
						attempt === 0 ? 100 : attempt === 1 ? 300 : 500,
					);
				}
				return;
			}

			initEditor();
		};

		initTimerRef.current = setTimeout(() => attemptInit(), 100);

		return () => {
			if (initTimerRef.current) {
				clearTimeout(initTimerRef.current);
				initTimerRef.current = null;
			}
			editorInitializingRef.current = false;
		};
	}, [editorId, rule.id, shouldShowGlobalMessageOption, useGlobalMessage]);

	return (
		<>
			{shouldShowGlobalMessageOption && (
				<div className="contentgate-label-input-pair contentgate-rule-action flex gap-6 items-start md:items-center flex-col md:flex-row">
					<label className="contentgate-label-container max-w-[300px] w-full">
						<span className="contentgate-target-content-label text-sm font-medium">
							{__("Restriction Message", "contentgate")}
						</span>
					</label>
					<div className="contentgate-input-container">
						<div className="contentgate-checkbox-radio-group flex gap-2 flex-col sm:flex-row">
							<label
								className={`contentgate-checkbox-radio-option flex items-center gap-2 px-3 py-2 border min-h-[38px] rounded-[4px] ${
									useGlobalMessage
										? "is-checked border-primary"
										: ""
								}`}
							>
								<input
									type="radio"
									name={`message-type-${rule.id}`}
									value="global"
									checked={useGlobalMessage}
									onChange={() =>
										onUseGlobalMessageChange(true)
									}
									className={`contentgate-checkbox-radio-input !mt-[0.5px] ${useGlobalMessage ? "!border-primary !accent-primary" : "!border-border"}`}
								/>
								<span className="contentgate-checkbox-radio-label text-sm">
									{__(
										"Use global restriction message",
										"contentgate",
									)}
								</span>
							</label>
							{isProAccess() && (
								<label
									className={`contentgate-checkbox-radio-option flex items-center gap-2 px-3 py-2 border min-h-[38px] rounded-[4px] ${
										!useGlobalMessage
											? "is-checked border-primary"
											: ""
									}`}
								>
									<input
										type="radio"
										name={`message-type-${rule.id}`}
										value="custom"
										checked={!useGlobalMessage}
										onChange={() =>
											onUseGlobalMessageChange(false)
										}
										className={`contentgate-checkbox-radio-input !mt-[0.5px] ${!useGlobalMessage ? "!border-primary !accent-primary" : "!border-border"}`}
									/>
									<span className="contentgate-checkbox-radio-label">
										{__("Custom message", "contentgate")}
									</span>
								</label>
							)}
						</div>
					</div>
				</div>
			)}
			{!useGlobalMessage && (
				<div className="contentgate-title-body-pair contentgate-rule-action-input-container cgra-message-input-container flex items-center gap-6">
					<label className="contentgate-label-container hidden md:max-w-[300px] w-full">
						<span className="contentgate-target-content-label"></span>
					</label>
					<div className="contentgate-body w-full">
						<div className="wp-editor-container">
							<div
								className="wp-core-ui wp-editor-wrap tmce-active"
								id={`wp-${editorId}-wrap`}
							>
								<div id={`wp-${editorId}-editor-container`}>
									<textarea
										id={editorId}
										ref={editorRef}
										defaultValue={message || ""}
										className="wp-editor-area"
									/>
								</div>
							</div>
						</div>
					</div>
				</div>
			)}
		</>
	);
};

export default MessageAction;
