// Copyright (c) 2015, JINGROW and Contributors
// MIT License. See license.txt

jingrow.ui.form.on("PageType", {
	onload: function (frm) {
		if (frm.is_new() && !frm.pg?.fields) {
			jingrow.listview_settings["PageType"].new_pagetype_dialog();
		}
		frm.call("check_pending_migration");

		// Setup module field filtering
		frm.set_query("module", () => {
			if (frm.pg.package) {
				return {
					filters: { package: frm.pg.package }
				};
			}
		});

		// Clear module when package changes
		frm.set_df_property("package", "on_change", function() {
			if (frm.is_dirty("package")) {
				frm.set_value("module", null);
			}
		});
	},

	before_save: function (frm) {
		let form_builder = jingrow.form_builder;
		if (form_builder?.store) {
			let fields = form_builder.store.update_fields();

			// if fields is a string, it means there is an error
			if (typeof fields === "string") {
				jingrow.throw(fields);
			}
		}

		// Normalize package: avoid saving objects or "0"
		if (frm.pg) {
			if (typeof frm.pg.package === "object" && frm.pg.package) {
				let inferred = null;
				try {
					inferred = frm.pg.package.name || frm.pg.package.package || frm.pg.package.value || frm.pg.package.message?.package || null;
				} catch (e) {}
				frm.set_value("package", inferred || null);
			}
			if (frm.pg.package === "0") {
				frm.set_value("package", null);
			}
		}
	},

	after_save: function (frm) {
		if (
			jingrow.form_builder &&
			jingrow.form_builder.pagetype === frm.pg.name &&
			jingrow.form_builder.store
		) {
			jingrow.form_builder.store.fetch();
		}
	},

	refresh: function (frm) {
		// Ensure label and required state for package field
		frm.set_df_property("package", "label", __("Package"));
		frm.set_df_property("package", "reqd", 0);

		// Auto-set package from existing module (for backward compatibility)
		if (!frm.pg.package && frm.pg.module) {
			jingrow.db.get_value("Module Def", frm.pg.module, "package").then(pkg => {
				// Ensure we only set string values, not objects
				if (pkg && typeof pkg === "string") {
					frm.set_value("package", pkg);
				}
			});
		}

		// Normalize package field to ensure it's a string or null
		if (frm.pg && frm.pg.package && typeof frm.pg.package === "object") {
			let inferred = null;
			try {
				inferred = frm.pg.package.name || frm.pg.package.package_name || frm.pg.package.value || null;
			} catch (e) {}
			frm.set_value("package", inferred || null);
		}

		frm.set_query("role", "permissions", function (pg) {
			if (pg.custom && jingrow.session.user != "Administrator") {
				return {
					query: "jingrow.core.pagetype.role.role.role_query",
					filters: [["Role", "name", "!=", "All"]],
				};
			}
		});

		if (jingrow.session.user !== "Administrator" || !jingrow.boot.developer_mode) {
			if (frm.is_new()) {
				frm.set_value("custom", 1);
			}
			frm.toggle_enable("custom", 0);
			frm.toggle_enable("is_virtual", 0);
			frm.toggle_enable("beta", 0);
		}

		if (!frm.is_new() && !frm.pg.istable) {
			if (frm.pg.issingle) {
				frm.add_custom_button(__("Go to {0}", [__(frm.pg.name)]), () => {
					window.open(`/app/${jingrow.router.slug(frm.pg.name)}`);
				});
			} else {
				frm.add_custom_button(__("Go to {0} List", [__(frm.pg.name)]), () => {
					window.open(`/app/${jingrow.router.slug(frm.pg.name)}`);
				});
			}
		}

		const customize_form_link = `<a href="/app/customize-form">${__("Customize Form")}</a>`;
		if (!jingrow.boot.developer_mode && !frm.pg.custom) {
			// make the document read-only
			frm.set_read_only();
			frm.dashboard.clear_comment();
			frm.dashboard.add_comment(
				__("PageTypes can not be modified, please use {0} instead", [customize_form_link]),
				"blue",
				true
			);
		} else if (jingrow.boot.developer_mode) {
			frm.dashboard.clear_comment();
			let msg = __(
				"This site is running in developer mode. Any change made here will be updated in code."
			);
			msg += "<br>";
			msg += __("If you just want to customize for your site, use {0} instead.", [
				customize_form_link,
			]);
			frm.dashboard.add_comment(msg, "yellow", true);
		}

		if (frm.is_new()) {
			frm.events.set_default_permission(frm);
			frm.set_value("default_view", "List");
		} else {
			frm.toggle_enable("engine", 0);
		}

		// set label for "In List View" for child tables
		frm.get_pagefield("fields", "in_list_view").label = frm.pg.istable
			? __("In Grid View")
			: __("In List View");

		frm.cscript.autoname(frm);
		frm.cscript.set_naming_rule_description(frm);
		frm.trigger("setup_default_views");

		render_form_builder(frm);
	},

	istable: (frm) => {
		if (frm.pg.istable && frm.is_new()) {
			frm.set_value("default_view", null);
		} else if (!frm.pg.istable && !frm.is_new()) {
			frm.events.set_default_permission(frm);
		}
	},

	set_default_permission: (frm) => {
		if (!(frm.pg.permissions && frm.pg.permissions.length)) {
			frm.add_child("permissions", { role: "System Manager" });
		}
	},

	is_tree: (frm) => {
		frm.trigger("setup_default_views");
	},

	is_calendar_and_gantt: (frm) => {
		frm.trigger("setup_default_views");
	},

	setup_default_views: (frm) => {
		jingrow.model.set_default_views_for_pagetype(frm.pg.name, frm);
	},

	on_tab_change: (frm) => {
		let current_tab = frm.get_active_tab().label;

		if (current_tab === "Form") {
			frm.footer.wrapper.hide();
			frm.form_wrapper.find(".form-message").hide();
			frm.form_wrapper.addClass("mb-1");
		} else {
			frm.footer.wrapper.show();
			frm.form_wrapper.find(".form-message").show();
			frm.form_wrapper.removeClass("mb-1");
		}
	},
});

jingrow.ui.form.on("PageField", {
	form_render(frm, pagetype, pagename) {
		frm.trigger("setup_fetch_from_fields", pagetype, pagename);
	},

	fieldtype: function (frm) {
		frm.trigger("max_attachments");
	},

	fields_add: (frm) => {
		frm.trigger("setup_default_views");
	},
});

function render_form_builder(frm) {
	if (jingrow.form_builder && jingrow.form_builder.pagetype === frm.pg.name) {
		jingrow.form_builder.setup_page_actions();
		jingrow.form_builder.store.fetch();
		return;
	}

	if (jingrow.form_builder) {
		jingrow.form_builder.wrapper = $(frm.fields_dict["form_builder"].wrapper);
		jingrow.form_builder.frm = frm;
		jingrow.form_builder.pagetype = frm.pg.name;
		jingrow.form_builder.customize = false;
		jingrow.form_builder.init(true);
		jingrow.form_builder.store.fetch();
	} else {
		jingrow.require("form_builder.bundle.js").then(() => {
			jingrow.form_builder = new jingrow.ui.FormBuilder({
				wrapper: $(frm.fields_dict["form_builder"].wrapper),
				frm: frm,
				pagetype: frm.pg.name,
				customize: false,
			});
		});
	}
}

extend_cscript(cur_frm.cscript, new jingrow.model.PageTypeController({ frm: cur_frm }));
