import Header from "@Front/Components/DesignSystem/Header";
import Version from "@Front/Components/DesignSystem/Version";
import classNames from "classnames";
import Image, { StaticImageData } from "next/image";
import React, { ReactNode, useEffect, useRef } from "react";

import classes from "./classes.module.scss";
import { useWindowSize } from "@uidotdev/usehooks";

type IProps = {
	title: string;
	children?: ReactNode;
	/**
	 * @description scroll top with number or disabled with null
	 */
	scrollTop?: number | null;
	image: StaticImageData;
	type?: "background" | "image";
	showHeader?: boolean;
};

export default function DefaultDoubleSidePage(props: IProps) {
	const { title, children, scrollTop = 0, image, type = "background", showHeader = false } = props;

	useEffect(() => {
		window.document.title = title;
		if (scrollTop !== null) {
			window.scrollTo(0, scrollTop);
		}
	}, [scrollTop, title]);

	useEffect(() => {
		// make second element ref height same as first element ref height
		const resizeObserver = new ResizeObserver(() => {
			if (secondElementRef.current && firstElementRef.current) {
				console.log("Recalculate");
				if (secondElementRef.current.clientHeight !== 0) {
					secondElementRef.current.style.height = `0px`;
				}

				secondElementRef.current.style.height = `${firstElementRef.current.clientHeight}px`;
			}
		});

		if (firstElementRef.current) {
			resizeObserver.observe(firstElementRef.current);
		}

		return () => resizeObserver.disconnect();
	}, []);

	const firstElementRef = useRef<HTMLDivElement>(null);
	const secondElementRef = useRef<HTMLDivElement>(null);

	return (
		<div className={classes["root"]}>
			<Header isUserConnected={showHeader} />
			<div className={classes["content"]}>
				<div className={classNames(classes["sides"], classes["side-left"])} ref={firstElementRef}>
					{children}
				</div>
				{type === "image" && (
					<div className={classNames(classes["sides"], classes["image-container"])} ref={secondElementRef}>
						<Image alt={"right side image"} src={image} className={classes["image"]} />
					</div>
				)}
				{type === "background" && (
					<div className={classNames(classes["sides"], classes["background-image-container"])} ref={secondElementRef}>
						<Image alt={"right side image"} src={image} className={classes["background-image"]} priority />
					</div>
				)}
			</div>
			<Version />
		</div>
	);
}
