import { createContext, useContext, 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);
	};

	return (
		<ModalsManagerContext.Provider
			value={{
				showModal,
				closeModal,
			}}
		>
			{children}
			{showBackdrop && <OverlayBackdrop />}
			{modalElement && modalElement}
		</ModalsManagerContext.Provider>
	);
};

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

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