import { useEffect, useLayoutEffect, useRef, useState } from "react";

import ResizeHandle from "./ResizeHandle";

import * as S from "./style";

const MIN_WIDTH = 368;

const ResizePanel = (props: IResizePanelProps): JSX.Element => {
	const { leftPanel, rightPanel, fixed = true, full = false, disabled } = props;

	const [rwidth, setRwidth] = useState(MIN_WIDTH);
	const [containerWidth, setContainerWidth] = useState(0);
	const rightPanelRef = useRef<HTMLDivElement>(null);
	const containerRef = useRef<HTMLDivElement>(null);

	useLayoutEffect(() => {
		if (containerRef.current) {
			setContainerWidth(containerRef.current.offsetWidth);
		}
	}, []);

	const calculateFixedPanelMinWidth = (currentWidth: number) => {
		const width = containerWidth || window.innerWidth;
		const minWidth = Math.max(500, width - currentWidth - 32);
		return `${minWidth}px`;
	};

	useEffect(() => {
		const updateWidth = () => {
			requestAnimationFrame(() => {
				if (rightPanelRef.current) {
					setRwidth(rightPanelRef.current.offsetWidth);
				}
			});
		};

		updateWidth();

		window.addEventListener("resize", updateWidth);
		return () => window.removeEventListener("resize", updateWidth);
	}, []);

	useEffect(() => {
		const resizeObserver = new ResizeObserver(() => {
			if (containerRef.current) {
				setContainerWidth(containerRef.current.offsetWidth);
			}
		});

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

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

	const resize = (value: number) => {
		if (value > MIN_WIDTH) setRwidth(value);
	};

	return (
		<div ref={containerRef} style={{ display: "flex", width: "100%", height: "100%" }}>
			<S.LeftPanel data-testid="left-panel">
				{fixed ? (
					<S.FixedPanel
						full={full}
						data-testid="fixed-panel"
						style={{ minWidth: rwidth ? calculateFixedPanelMinWidth(rwidth) : "auto" }}
					>
						{leftPanel}
					</S.FixedPanel>
				) : (
					leftPanel
				)}
			</S.LeftPanel>
			{!disabled && <ResizeHandle onMouseMove={resize} currentWidth={rwidth} />}
			<S.RightPanel ref={rightPanelRef} data-testid="right-panel" style={{ width: rwidth ? `${rwidth}px` : "auto" }}>
				{rightPanel}
			</S.RightPanel>
		</div>
	);
};

export interface IResizePanelProps {
	leftPanel: JSX.Element | JSX.Element[];
	rightPanel: JSX.Element | JSX.Element[];
	fixed?: boolean;
	full?: boolean;
	disabled?: boolean;
}

export default ResizePanel;
