jingrow.pages["workflow-builder"].on_page_load = function (wrapper) {
	jingrow.ui.make_app_page({
		parent: wrapper,
		title: __("Workflow Builder"),
		single_column: true,
	});

	// hot reload in development
	if (jingrow.boot.developer_mode) {
		jingrow.hot_update = jingrow.hot_update || [];
		jingrow.hot_update.push(() => load_workflow_builder(wrapper));
	}
};

jingrow.pages["workflow-builder"].on_page_show = function (wrapper) {
	load_workflow_builder(wrapper);
};

function load_workflow_builder(wrapper) {
	let route = jingrow.get_route();
	let $parent = $(wrapper).find(".layout-main-section");
	$parent.empty();

	if (route.length > 1) {
		jingrow.require("workflow_builder.bundle.js").then(() => {
			jingrow.workflow_builder = new jingrow.ui.WorkflowBuilder({
				wrapper: $parent,
				page: wrapper.page,
				workflow: route[1],
			});
		});
	} else {
		let d = new jingrow.ui.Dialog({
			title: __("Create or Edit Workflow"),
			fields: [
				{
					label: __("Action"),
					fieldname: "action",
					fieldtype: "Select",
					options: [
						{ label: __("Create New"), value: "Create" },
						{ label: __("Edit Existing"), value: "Edit" },
					],
					change() {
						let action = d.get_value("action");
						d.get_primary_btn().text(action === "Create" ? __("Create") : __("Edit"));
					},
				},
				{
					label: __("Select Document Type"),
					fieldname: "pagetype",
					fieldtype: "Link",
					options: "PageType",
					filters: {
						istable: 0,
					},
					reqd: 1,
					default: jingrow.route_options ? jingrow.route_options.pagetype : null,
				},
				{
					label: __("New Workflow Name"),
					fieldname: "workflow_name",
					fieldtype: "Data",
					depends_on: (pg) => pg.action === "Create",
					mandatory_depends_on: (pg) => pg.action === "Create",
				},
				{
					label: __("Select Workflow"),
					fieldname: "workflow",
					fieldtype: "Link",
					options: "Workflow",
					only_select: 1,
					depends_on: (pg) => pg.action === "Edit",
					get_query() {
						return {
							filters: {
								document_type: d.get_value("pagetype"),
							},
						};
					},
					mandatory_depends_on: (pg) => pg.action === "Edit",
				},
			],
			primary_action_label: __("Edit"),
			primary_action({ action, pagetype, workflow, workflow_name }) {
				if (action === "Edit") {
					jingrow.set_route("workflow-builder", workflow);
				} else if (action === "Create") {
					d.get_primary_btn().prop("disabled", true);
					jingrow.db
						.insert({
							pagetype: "Workflow",
							workflow_name: workflow_name,
							document_type: pagetype,
						})
						.then((pg) => {
							jingrow.set_route("workflow-builder", pg.name);
						})
						.finally(() => {
							d.get_primary_btn().prop("disabled", false);
						});
				}
			},
		});
		d.set_value("action", "Create");
		d.show();
	}
}
