import webpack from "../webpack";
import { React } from "../common";

const { findByProps, findByDisplayName, findByDisplayNameAll } = webpack;

const { openModal } = findByProps("openModalLazy");
const Colors = findByProps("button", "colorRed");
const ConfirmModal = findByDisplayName("ConfirmModal");
const Markdown = findByDisplayNameAll("Markdown")[1];

function rawOpenConfirmModal(
	Component: any,
	props: any,
	insideProps: any,
	insideContent: any
) {
	if (insideProps === undefined) {
		insideProps = {};
	}
	if (insideContent === undefined) {
		insideContent = "";
	}
	let confirmed;
	openModal((e: { transitionState: any; onClose: () => void }) => {
		if (e.transitionState === 3) {
			return false; //TODO: the fuck does this do?
		}

		return (
			<ConfirmModal
				transitionState={e.transitionState}
				onClose={() => (confirmed = false)}
				onCancel={() => {
					confirmed = false;
					e.onClose();
				}}
				onConfirm={() => {
					confirmed = true;
					e.onClose();
				}}
				{...props}
			>
				<Component {...insideProps}>{insideContent}</Component>
			</ConfirmModal>
		);
	});
	while (confirmed === undefined) {}
	return confirmed;
}

function openConfirmModal(
	content: string,
	type: string,
	opts: {
		header: string;
		confirmText: string;
		cancelText: string;
		color: any;
	}
) {
	let buttonColor;
	if (!!opts.color) {
		buttonColor = opts.color;
	} else {
		switch (type) {
			case "danger":
				buttonColor = Colors.colorRed;
				break;
			case "confirm":
				buttonColor = Colors.colorGreen;
				break;
			default:
				buttonColor = Colors.colorBrandNew;
				break;
		}
	}
	return rawOpenConfirmModal(
		Markdown,
		{
			header: opts.header ?? "Default Modal Header",
			confirmText: opts.confirmText ?? "Confirm",
			cancelText: opts.cancelText ?? "Cancel",
			confirmButtonColor: buttonColor
		},
		{
			editable: false
		},
		content ?? "Default modal content"
	);
}

export default {
	rawOpenConfirmModal,
	openConfirmModal
};
