import { Modal } from "antd";
import { JSX, ReactNode, createContext, useContext, useState } from "react";

type ModalProviderProps = {
	children: ReactNode;
};
const ModalContext = createContext<IModal>(undefined);

export function useModal() {
	return useContext(ModalContext);
}

export let modalObj: IModal = null;

export function ModalProvider({ children }: ModalProviderProps) {
	const [isOpen, setIsOpen] = useState(false);
	const [confirmData, setConfirmData] = useState<IConfirmMessageData>(undefined);

	function handleOpen(data: IConfirmMessageData): void {
		setConfirmData(data);
		setIsOpen(true);
	}

	const handleClose = () => setIsOpen(false);

	function handleConfirm(): void {
		confirmData?.handleConfirm && confirmData?.handleConfirm();
		handleClose();
	}

	function handleCancel(): void {
		confirmData?.handleCancel && confirmData?.handleCancel();
		handleClose();
	}

	const modal: IModal = modalObj = {
		isOpen,
		handleOpen,
		handleClose,
		confirmData,
	};

	return (
		<ModalContext.Provider value={modal}>
			{children}
			<Modal title={confirmData?.title} open={isOpen} onOk={handleConfirm} onCancel={handleCancel} cancelText={confirmData?.cancelStr} style={{ top: "40%" }}>
				<p>{confirmData?.content}</p>
			</Modal>
		</ModalContext.Provider>
	);
}


export interface IModal {
	isOpen: boolean;
	handleOpen: (data: IConfirmMessageData) => void;
	handleClose: () => void;
	confirmData: IConfirmMessageData;
}

export interface IConfirmMessageData {
	title?: string;
	subTitle?: string;
	content?: string;
	enterStr?: string;
	cancelStr?: string;
	isShowCancel?: boolean;
	isOrangeButton?: boolean;
	isNeedClickConfirmClosePanel?: boolean;
	handleCancel?: () => unknown;
	handleConfirm?: (...args: any) => unknown;
	render?: (data?: any) => ReactNode;
	newRender?: (data?: any) => JSX.Element;
	textAlign?: "center" | "left" | "right";
}