import { createContext, useContext, useEffect, useState } from "react";
import { View } from "react-native";

export interface ImodalsManagerContext {
	showModal(element: React.ReactElement): void;
	closeModal(): void;
}

export const ModalsManagerContext = createContext<ImodalsManagerContext>({
	showModal: () => {},
	closeModal: () => {},
});

export const ModalsManagerProvider = ({ children }: { children: React.ReactNode }) => {
	const [showBackdrop, setShowBackdrop] = useState(false);

	const [modalElement, setModalElement] = useState<React.ReactElement | null>(null);

	const showModal = (element: React.ReactElement) => {
		setModalElement(element);
		setShowBackdrop(true);
	};

	const closeModal = () => {
		setModalElement(null);
		setShowBackdrop(false);
	};

	useEffect(() => {
		return () => {
			setShowBackdrop(false);
			setModalElement(null);
		};
	}, []);

	return (
		<ModalsManagerContext.Provider
			value={{
				showModal,
				closeModal,
			}}
		>
			{children}

			{modalElement && (
				<>
					<OverlayBackdrop />
					{modalElement}
				</>
			)}
		</ModalsManagerContext.Provider>
	);
};

export const useModalsManagerContext = () => {
	return useContext(ModalsManagerContext);
};

export const OVERLAY_BACKDROP_Z_INDEX = 10;

const OverlayBackdrop = () => {
	return (
		<View
			style={{
				flex: 1,
				width: "100%",
				height: "100%",
				// justifyContent: "center",
				// alignItems: "center",
				zIndex: OVERLAY_BACKDROP_Z_INDEX,
				backgroundColor: "black",
				opacity: 0.5,
				position: "absolute",
			}}
		/>
	);
};
