import { useCallback, useEffect, useState } from "react";

import { OcassionalToast } from "@ax/components";
import { formatDate } from "@ax/helpers";
import type { ILanguage, ISocialState } from "@ax/types";

import { type Core, Preview } from "@griddo/core";
import * as components from "components";
import { builderSSR, SiteProvider, ssrHelpers } from "components";

const BrowserContent = (props: IProps) => {
	const {
		content,
		socials,
		cloudinaryName,
		siteLangs,
		siteID,
		theme,
		isPage,
		header,
		footer,
		languageID,
		pageLanguages,
		selectEditorID,
		moduleActions,
		renderer,
		selectHoverEditorID,
		shareEndDate,
	} = props;

	const API_URL = process.env.GRIDDO_API_URL || process.env.REACT_APP_API_ENDPOINT;
	const PUBLIC_API_URL = process.env.GRIDDO_PUBLIC_API_URL || process.env.REACT_APP_PUBLIC_API_ENDPOINT;
	const INSTANCE = process.env.REACT_APP_INSTANCE || process.env.GRIDDO_REACT_APP_INSTANCE;

	const useInstanceExternalAssets = useCallback(() => {
		if (builderSSR?.onRenderBody) {
			builderSSR.onRenderBody(ssrHelpers);
		}
	}, []);

	const [showBanner, setShowBanner] = useState(true);

	// biome-ignore lint/correctness/useExhaustiveDependencies: fix
	useEffect(useInstanceExternalAssets, [useInstanceExternalAssets]);

	return (
		<SiteProvider
			cloudinaryCloudName={cloudinaryName}
			theme={theme}
			socials={socials}
			siteLangs={siteLangs}
			selectEditorID={selectEditorID}
			renderer={renderer}
			apiUrl={API_URL}
			publicApiUrl={PUBLIC_API_URL}
			instance={INSTANCE}
			siteId={siteID}
			moduleActions={moduleActions}
			selectHoverEditorID={selectHoverEditorID}
		>
			{renderer === "sharedPage" && showBanner && (
				<OcassionalToast
					message={`This draft link expires on ${shareEndDate ? formatDate(new Date(shareEndDate)) : "..."}`}
					icon="scheduled"
					onDismiss={() => setShowBanner(false)}
				/>
			)}
			<Preview
				isPage={isPage}
				apiUrl={API_URL}
				library={components}
				content={content}
				header={header}
				footer={footer}
				languageId={languageID}
				pageLanguages={pageLanguages}
			/>
		</SiteProvider>
	);
};

interface IProps {
	content: any;
	socials: ISocialState;
	cloudinaryName: string | null;
	siteLangs: ILanguage[];
	siteID?: number;
	theme: string;
	isPage: boolean;
	header?: any;
	footer?: any;
	languageID: number;
	pageLanguages: Core.Page["pageLanguages"];
	renderer: "editor" | "preview" | "forms" | "sharedPage";
	selectEditorID?(
		selectedComponent: { editorID: number; component: any; type: string; parentEditorID: number },
		parentComponent: string | undefined | null,
		e: React.SyntheticEvent,
	): void;
	selectHoverEditorID?(editorID: number, parentEditorID: number): void;
	moduleActions?: {
		deleteModuleAction?(editorID: number): void;
		duplicateModuleAction?(editorID: number): void;
		copyModuleAction?(editorID: number): void;
	};
	shareEndDate?: string | null;
}

export default BrowserContent;
