import ErrorModal from "@components/modals/ErrorModal";
import LoadingModal from "@components/modals/LoadingModal";
import { createContext, useContext, useState } from "react";
import { View } from "react-native";

export interface IoverlayContext {
	showOverlay(): void;
	hideOverlay(): void;
}

export const OverlayContext = createContext<IoverlayContext>({
	showOverlay: () => {},
	hideOverlay: () => {},
});

export const OverlayProvider = ({ children }: { children: React.ReactNode }) => {
	const [showBackdrop, setShowBackdrop] = useState(true);
	const [loadingModalVisible, setLoadingModalVisible] = useState(false);
	const [errorModalVisible, setErrorModalVisible] = useState(true);

	const showOverlay = () => {
		setShowBackdrop(true);
		setLoadingModalVisible(true);
	};

	const hideOverlay = () => {
		setShowBackdrop(false);
		setLoadingModalVisible(false);
	};

	return (
		<OverlayContext.Provider
			value={{
				showOverlay,
				hideOverlay,
			}}
		>
			{children}
			{showBackdrop && <OverlayBackdrop />}

			{loadingModalVisible && <LoadingModal />}
			{errorModalVisible && <ErrorModal />}
		</OverlayContext.Provider>
	);
};

export const useOverlayContext = () => {
	return useContext(OverlayContext);
};

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