import { __ } from "@wordpress/i18n";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../ui/Tooltip";
import { Info } from "lucide-react";
import { TinyMCEEditor } from "../../../types";
import SmartTagsButton from "../settings/SmartTagsButton";

type Props = {
	message: string;
	setMessage: React.Dispatch<React.SetStateAction<string>>;
	defaultMessage: string;
};

const GeneralSettings = ({ message, setMessage, defaultMessage }: Props) => {
	const editorId = "contentgate-action-global-message-editor";
	const isMountedRef = useRef(true);
	const editorInitializedRef = useRef(false);
	const editorInitializingRef = useRef(false);
	const initTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
	const changeHandlerRef = useRef<(() => void) | null>(null);

	const cleanupEditor = useCallback(() => {
		if (initTimerRef.current) {
			clearTimeout(initTimerRef.current);
			initTimerRef.current = null;
		}

		if (changeHandlerRef.current && window.tinymce) {
			const editor = window.tinymce.get(editorId);
			if (editor) {
				try {
					editor.off("change keyup", changeHandlerRef.current);
					changeHandlerRef.current = null;
				} catch (error) {
					console.error(
						"Failed to remove editor event listeners:",
						error,
					);
				}
			}
		}

		if (window.wp?.editor && window.tinymce) {
			const editor = window.tinymce.get(editorId);
			if (editor) {
				try {
					const currentContent = editor.getContent();
					if (currentContent) {
						setMessage(currentContent);
					}

					window.wp.editor.remove(editorId);
					editorInitializedRef.current = false;
					editorInitializingRef.current = false;
				} catch (error) {
					console.error("Failed to cleanup editor:", error);
				}
			}
		}
	}, [editorId]);

	const initializeEditor = useCallback(
		(contentToSet: string) => {
			if (!isMountedRef.current) return;
			if (editorInitializingRef.current || editorInitializedRef.current)
				return;
			if (!window.wp?.editor) return;

			const editorElement = document.getElementById(
				editorId,
			) as HTMLTextAreaElement | null;
			if (!editorElement) return;

			if (window.tinymce?.get(editorId)) {
				console.warn("Editor already exists, skipping initialization");
				return;
			}

			editorInitializingRef.current = true;

			if (editorElement && contentToSet) {
				editorElement.value = contentToSet;
			}

			try {
				window.wp.editor.initialize(editorId, {
					quicktags: false,
					mediaButtons: true,
					tinymce: {
						toolbar1:
							"undo,redo,formatselect,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) => {
							editor.on("init", () => {
								if (
									contentToSet &&
									editor.getContent() !== contentToSet
								) {
									editor.setContent(contentToSet);
								}
							});
						},

						init_instance_callback: (editor: TinyMCEEditor) => {
							editorInitializedRef.current = true;
							editorInitializingRef.current = false;

							if (!isMountedRef.current) return;

							if (
								contentToSet &&
								editor.getContent() !== contentToSet
							) {
								editor.setContent(contentToSet);
							}

							const handleChange = () => {
								if (isMountedRef.current) {
									const content =
										window.wp?.editor?.getContent(
											editorId,
										) || "";
									setMessage(content);
								}
							};

							changeHandlerRef.current = handleChange;

							setTimeout(() => {
								if (isMountedRef.current) {
									editor.on("change keyup", handleChange);
								}
							}, 150);
						},
					},
				});
			} catch (error) {
				console.error("Failed to initialize editor:", error);
				editorInitializingRef.current = false;
			}
		},
		[editorId],
	);

	const attemptInitialization = useCallback(
		(content: string, attempt = 0) => {
			if (editorInitializedRef.current && window.tinymce?.get(editorId)) {
				return;
			}

			const editorElement = document.getElementById(editorId);

			if (!editorElement || !window.wp?.editor) {
				if (attempt < 3) {
					const delays = [100, 300, 500];
					initTimerRef.current = setTimeout(
						() => attemptInitialization(content, attempt + 1),
						delays[attempt],
					);
				} else {
					console.error(
						"Failed to initialize editor after 3 attempts",
					);
				}
				return;
			}

			initializeEditor(content);
		},
		[editorId, initializeEditor],
	);

	useEffect(() => {
		isMountedRef.current = true;

		return () => {
			isMountedRef.current = false;
			cleanupEditor();
		};
	}, [cleanupEditor]);

	useEffect(() => {
		const contentToUse = message || defaultMessage;

		initTimerRef.current = setTimeout(() => {
			attemptInitialization(contentToUse);
		}, 100);

		return () => {
			if (initTimerRef.current) {
				clearTimeout(initTimerRef.current);
				initTimerRef.current = null;
			}
		};
	}, [defaultMessage, attemptInitialization]);

	return (
		<>
			<h6 className="text-[16px] font-semibold pb-4 border-b border-border ">
				{__("Restriction Settings", "contentgate")}
			</h6>
			<div className="contentgate-label-input-pair contentgate-rule-action flex gap-6 items-start flex-col md1:flex-row">
				<label className="contentgate-label-container flex items-center gap-2 max-w-full md:max-w-[300px] w-full">
					<span className="contentgate-target-content-label text-sm font-medium">
						{__("Global Restriction Message", "contentgate")}
					</span>
					<Tooltip>
						<TooltipTrigger>
							<Info size={14} />
						</TooltipTrigger>
						<TooltipContent className="z-[9999]" side="bottom">
							<p>
								{__(
									"Default message for all restricted content. This message will be shown to users when they do not have access to content.",
									"contentgate",
								)}
							</p>
						</TooltipContent>
					</Tooltip>
				</label>
				<div className="contentgate-input-container flex-1 w-full md:w-auto flex flex-col gap-[10px]">
					<div className="contentgate-body w-full">
						<div className="mb-2 flex justify-end">
							<SmartTagsButton
								editorId={editorId}
								onTagInsert={(tag: string) => {
									if (!window.tinymce) return;
									const editor = window.tinymce.get(editorId);
									if (!editor) return;
									editor.execCommand(
										"mceInsertContent",
										false,
										tag,
									);
									editor.save();
									setMessage(editor.getContent());
								}}
							/>
						</div>
						<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}
										defaultValue={defaultMessage || ""}
										className="wp-editor-area"
									/>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</>
	);
};

export default GeneralSettings;
