const { __ } = wp.i18n;

const { useState, useEffect } = wp.element;

const ActivitySummary = ( { commentAutoDrafts, suggestionAutoDrafts, setDifference } ) => {

	const [ hasAccordian, setHasAccordian ] = useState( false );
	const [ hasAccordianSuggestions, setHhasAccordianSuggestions ] = useState( false );
	const [ threads, setThreads ] = useState(null);
	const [ loading, setLoading ] = useState(true);
	const [ error, setError ] = useState(null);

	var resolveCounts = 0,
	opencmntsCounts = 0,
	userCounter = "",
	storeUserCounter = "",
	lastUser = "",
	diff = "",
	uniqueChars = [],
	lastUserProfile = "",
	counterArr = [],
	counterIndex = 0,
	userImages = "",
	userRoles = "",
	userFullInfo = "",
	totalSuggestions = 0,
	insertionSuggestions = 0,
	deletionSuggestions = 0,
	formattingSuggestions = 0,
	totalComments = 0,
	openSuggestions = 0,
	acceptedSuggestions = 0,
	rejectedSuggestions = 0;
var threadsOrgLength =
	null === threads ? 0 : threads.length;
var suggestionUsersValues = "",
	suggestionUsersImages = "",
	suggestionUsersRoles = "",
	suggestionUserFullInfo = "",
	suggestionCounterArr = [],
	suggestionsIndex = 0,
	uniqueSuggestionUsers = [],
	storeUniqueSuggestionUser = "";
	const boardIdsCount = wp.data.select('mdstore').getBoardIds()?.filter(id => !id.startsWith('el')).length || 0;

	useEffect(() => {
		const fetchThreads = () => {
			const postID = wp.data.select("core/editor").getCurrentPostId() ?? document.getElementById("post_ID").value;
			if (!postID) {
				setError("Editor is loading slowly. Please refresh the page");
				setLoading(false);
				return;
			}

			const isFallback = multicollabActivityL10n.apiUrl.includes('rest_route=');
			const baseUrl = multicollabActivityL10n.apiUrl.replace(/\/+$/, ''); // remove trailing slash
			const route = '/multicollab/v2/activities'; // always has leading slash

			const url = isFallback
			  ? `${baseUrl}${route}&postID=${postID}` // NO slash between baseUrl and route
			  : `${baseUrl}${route}?postID=${postID}`; // regular format

			fetch(url, {
				method: 'GET',
				headers: {
					"X-WP-Nonce": multicollabActivityL10n.nonce,
				},
			})
				.then(async (res) => {
					if (!res.ok) {
						const errorText = await res.text();

						// Detect nonce expiration and reload
						if (res.status === 403 && errorText.toLowerCase().includes("nonce")) {
							throw new Error("Nonce expired. Reloading the page...");
						}

						throw new Error(`Network error: ${res.status} - ${errorText}`);
					}

					return res.json();
				})
				.then((data) => {
					setThreads(data.threads?.length > 0 ? data.threads : null);
				})
				.catch((error) => {
					console.error("Fetch error:", error);
					setError(error.message || "Unknown error occurred");

					// Auto-reload on nonce error
					if (error.message?.toLowerCase().includes("nonce expired")) {
						setTimeout(() => {
							window.location.reload();
						}, 1500); // Optional delay to show error before reload
					}
				})
				.finally(() => {
					setLoading(false);
				});
		};

		fetchThreads();
	}, []);

	if (loading) {
		//return <div>Loading...</div>; // Loading state
		return (
			<div class="cf-summary">
				<div class="comment-summary-row">
					<div class="summary-accordion">
						<span>{__(
							"Comments",
							"commenting-feature"
							)}</span>
						<span>
							<svg
								width="24"
								height="24"
								viewBox="0 0 24 24"
								xmlns="http://www.w3.org/2000/svg"
								className="components-panel__arrow"
								role="img"
								aria-hidden="true"
								focusable="false"
							>
								<path d="M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"></path>
							</svg>
						</span>
					</div>
					<section></section>
				</div>
			</div>
		);
	}

	if (error) {
		return <div>Error: {error}</div>; // Error state
	}

	return (
		<div className="cf-summary">
			{null === threads && (
			<div className="comment-summary-row">
				<div
				className={
					true === hasAccordian &&
					"1" !== multicollabRolePermissions.hide_comment
					? "summary-accordion active-accordion"
					: "summary-accordion"
				}
				onClick={() => {
					setHasAccordian( prev => !prev )
				}}
				>
				<span>
					{__(
					"Comments",
					"commenting-feature"
					)}
				</span>
				{true === hasAccordian ? (
					<span>
					<svg
						width="24"
						height="24"
						viewBox="0 0 24 24"
						xmlns="http://www.w3.org/2000/svg"
						className="components-panel__arrow"
						role="img"
						aria-hidden="true"
						focusable="false"
					>
						<path d="M6.5 12.4L12 8l5.5 4.4-.9 1.2L12 10l-4.5 3.6-1-1.2z"></path>
					</svg>
					</span>
				) : (
					<span>
					<svg
						width="24"
						height="24"
						viewBox="0 0 24 24"
						xmlns="http://www.w3.org/2000/svg"
						className="components-panel__arrow"
						role="img"
						aria-hidden="true"
						focusable="false"
					>
						<path d="M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"></path>
					</svg>
					</span>
				)}
				</div>
				<section>
				{true === hasAccordian && (
					<div>
					<label className="comments-row">
						{__(
						"Total Comments",
						"commenting-feature"
						)}{" "}
						<span>0</span>
					</label>
					<label className="comments-row">
						{__(
						"Open Comments",
						"commenting-feature"
						)}{" "}
						<span>0</span>
					</label>
					<label className="comments-row">
						{__(
						"Resolved Comments",
						"commenting-feature"
						)}{" "}
						<span>0</span>
					</label>
					</div>
				)}
				</section>
			
			</div>
			)}

			{ undefined !== threads &&
			null !== threads && (
				<section>
				<div className="last-activity-section">
					<div className="comment-summary-last-activity-section">
					{__(
						"Last Edited By",
						"commenting-feature"
					)}{" "}
					</div>
					{threads.slice(0, 1).map((th) => {
					if (
						th.resolved === "false" &&
						th.type === "el" &&
						th.type !== undefined
					) {
						th.activities.map((activity) => {
						var afterChngThread = threads.length;
						lastUserProfile =
							threadsOrgLength === afterChngThread
							? th.lastUsersUrl
							: activity.userData.avatarUrl;
						lastUser = th.lastUser;
						var cmtEditedTime =
							threadsOrgLength === afterChngThread
							? th.lastEditedTime
							: th.updatedAt;
						diff =
							th.lastEditedTime !== undefined ||
							activity.timestamp !== undefined
							? timeAgo(cmtEditedTime)
							: "";
						});
						return (
						<div
							className="last-activity-row"
							key={th}
						>
							<span className="summary-user-avatar">
							<img
								src={lastUserProfile}
								alt={lastUser}
							/>
							</span>
							<span className="user-avtar-details">
							<span className="lastuser-name">
								{lastUser}
							</span>
							<span className="last-edited-time">
								{diff}
							</span>
							</span>
						</div>
						);
					}
					if (
						th.resolved === "true" &&
						th.type === "el" &&
						th.type !== undefined
					) {
						var afterChngThread = threads.length;
						lastUserProfile =
						threadsOrgLength === afterChngThread
							? th.lastUsersUrl
							: th.resolvedBy.avatarUrl;
						lastUser = th.lastUser;
						var resvEditedTime =
						threadsOrgLength === afterChngThread
							? th.lastEditedTime
							: th.updatedAt;
						diff =
						th.lastEditedTime !== undefined ||
							th.resolvedTimestamp !== undefined
							? timeAgo(resvEditedTime)
							: "";
						return (
						<div
							className="last-activity-row"
							key={th}
						>
							<span className="summary-user-avatar">
							<img
								src={lastUserProfile}
								alt={lastUser}
							/>
							</span>
							<span className="user-avtar-details">
							<span className="lastuser-name">
								{lastUser}
							</span>
							<span className="last-edited-time">
								{diff}
							</span>
							</span>
						</div>
						);
					}
					if (
						th.type === "sg" &&
						th.type !== undefined
					) {
						th.activities.map((activity) => {
						var afterChngThread = threads.length;
						lastUserProfile =
							threadsOrgLength === afterChngThread &&
							th.lastUsersUrl !== undefined
							? th.lastUsersUrl
							: activity.userData.avatarUrl;
						lastUser =
							th.lastUser === undefined
							? activity.userData.username
							: th.lastUser;
						var cmtEditedTime =
							threadsOrgLength === afterChngThread &&
							th.lastEditedTime !== undefined
							? th.lastEditedTime
							: th.updatedAt;
						diff =
							th.lastEditedTime !== undefined ||
							activity.timestamp !== undefined
							? timeAgo(cmtEditedTime)
							: "";
						});
						return (
						<div
							className="last-activity-row"
							key={th}
						>
							<span className="summary-user-avatar">
							<img
								src={lastUserProfile}
								alt={lastUser}
							/>
							</span>
							<span className="user-avtar-details">
							<span className="lastuser-name">
								{lastUser}
							</span>
							<span className="last-edited-time">
								{diff}
							</span>
							</span>
						</div>
						);
					}
					})}
				</div>
				{"1" !== multicollabRolePermissions.hide_comment && (
					<div
					className={
						false === hasAccordianSuggestions &&
						"1" !== multicollabRolePermissions.hide_comment
						? "summary-accordion active-accordion"
						: "summary-accordion"
					}
					onClick={() => {
						setHhasAccordianSuggestions( prev => !prev );
					}}
					>
					<span>
						{__(
						"Comments",
						"commenting-feature"
						)}
					</span>
					{true === hasAccordianSuggestions ? (
						<span>
						<svg
							width="24"
							height="24"
							viewBox="0 0 24 24"
							xmlns="http://www.w3.org/2000/svg"
							className="components-panel__arrow"
							role="img"
							aria-hidden="true"
							focusable="false"
						>
							<path d="M6.5 12.4L12 8l5.5 4.4-.9 1.2L12 10l-4.5 3.6-1-1.2z"></path>
						</svg>
						</span>
					) : (
						<span>
						<svg
							width="24"
							height="24"
							viewBox="0 0 24 24"
							xmlns="http://www.w3.org/2000/svg"
							className="components-panel__arrow"
							role="img"
							aria-hidden="true"
							focusable="false"
						>
							<path d="M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"></path>
						</svg>
						</span>
					)}
					</div>
				)}
				{"1" !== multicollabRolePermissions.hide_comment &&
					false === hasAccordianSuggestions && (
					<div className="accordian-panel">
						<div className="comments-row">
						<label className="comment-summary-total-comments">
							{__(
							"Total Comments",
							"commenting-feature"
							)}
						</label>
						{
							<div className="opencommentsvalue">
							{threads.map((th) => {
								if (
								th.type === "el" &&
								th.type !== undefined
								) {
								totalComments++;
								}
							})}
							<span>
								{totalComments - commentAutoDrafts}
							</span>
							</div>
						}
						</div>
						<div className="comments-row">
						<label className="comment-summary-open-comments">
							{__(
							"Open Comments",
							"commenting-feature"
							)}{" "}
						</label>
						{
							<div className="opencommentsvalue">
							{threads.map((th) => {
								if (
								th.resolved !== "true" &&
								th.type === "el"
								) {
								opencmntsCounts++;
								}
							})}
							<span>
								{opencmntsCounts -
								commentAutoDrafts}
							</span>
							</div>
						}
						</div>
						<div className="comments-row">
						<label className="comment-summary-resolved-comments">
							{__(
							"Resolved Comments",
							"commenting-feature"
							)}
						</label>
						{
							<div className="resolvedvalue">
							{threads.map((th) => {
								if (
								th.resolved === "true" &&
								th.type === "el"
								) {
								resolveCounts++;
								}
							})}
							<span>{resolveCounts}</span>
							</div>
						}
						</div>
					</div>
					)}

				</section>
			)}
		</div>
	);
};

export default ActivitySummary;