import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

import { pages, shareToken as shareTokenApi } from "@ax/api";
import { BrowserContent, ErrorPage, Loading } from "@ax/components";
import { getDefaultTheme, isReqOk } from "@ax/helpers";

import * as S from "./style";

const PublicPreview = () => {
	const { id: pageID, entity } = useParams<{ id: string; entity: string }>();
	const [state, setState] = useState<any>(null);
	const [isLoading, setIsLoading] = useState(false);
	const [tokenError, setTokenError] = useState<string | null>(null);
	const [shareEndDate, setShareEndDate] = useState<string | null>(null);

	// biome-ignore lint/correctness/useExhaustiveDependencies: TODO: fix this
	useEffect(() => {
		let isMounted = true;
		document.body.classList.add("preview");

		// Store preview credentials in sessionStorage for API calls
		if (pageID && entity) {
			sessionStorage.setItem("previewPageId", pageID);
			sessionStorage.setItem("previewEntity", entity);
		}

		const getPage = async () => {
			if (!isMounted) return;

			setIsLoading(true);

			const response = await pages.getPublicPage(parseInt(pageID), entity);
			if (isReqOk(response.status)) {
				setState(response.data);

				const shareResponse = await shareTokenApi.getShare(parseInt(pageID));
				if (isReqOk(shareResponse.status)) {
					setShareEndDate(shareResponse.data.endDate);
				}
			} else {
				setTokenError(response.status === 404 ? "404" : response.status === 410 ? "linkExpired" : "wrong");
			}

			setIsLoading(false);
		};

		getPage();

		return function cleanup() {
			isMounted = false;
			document.body.classList.remove("preview");
			// Clean up preview credentials when leaving preview
			sessionStorage.removeItem("previewPageId");
			sessionStorage.removeItem("previewEntity");
		};
	}, []);

	const globalTheme = getDefaultTheme();
	const theme = state?.site ? state.siteInfo.theme : globalTheme;
	const socials = state?.site ? state.siteInfo.socials : [];
	const langs = state?.site ? state.siteInfo.siteLanguages : [];
	const siteID = state?.siteInfo ? state.siteInfo.siteId : undefined;

	if (tokenError) {
		return <ErrorPage type={tokenError} />;
	}

	if (isLoading || !state) return <Loading />;

	const setBrowserRef = (ref: any) => {
		(window as any).browserRef = ref;
	};

	return (
		<S.Wrapper ref={setBrowserRef}>
			<BrowserContent
				cloudinaryName={state?.cloudinaryName}
				theme={theme}
				socials={socials}
				siteLangs={langs}
				siteID={siteID}
				isPage={true}
				content={state}
				header={state?.headerContent}
				footer={state?.footerContent}
				languageID={state?.language}
				pageLanguages={state?.pageLanguages}
				renderer="sharedPage"
				shareEndDate={shareEndDate}
			/>
		</S.Wrapper>
	);
};

export default PublicPreview;
