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 ImodalsManagerContext {
	showLoadingModal(): void;
	closeLoadingModal(): void;
	showErrorModal(): void;
	closeErrorModal(): void;

	showModal(element: React.ReactElement): void;
	closeModal(): void;
}

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

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

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

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

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

	const showErrorModal = () => {
		setShowBackdrop(true);
		setErrorModalVisible(true);
	};

	const closeErrorModal = () => {
		setShowBackdrop(false);
		setErrorModalVisible(false);
	};

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

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

	return (
		<ModalsManagerContext.Provider
			value={{
				showLoadingModal,
				closeLoadingModal,
				showErrorModal,
				closeErrorModal,
				showModal,
				closeModal,
			}}
		>
			{children}
			{showBackdrop && <OverlayBackdrop />}
			{modalElement && modalElement}

			{loadingModalVisible && <LoadingModal />}
			{errorModalVisible && <ErrorModal />}
		</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",
			}}
		/>
	);
};
