// Multiple Tax Articles per Sales Invoice Item row.
// Click the read-only "Tax Articles" cell -> a dialog opens with a Table MultiSelect
// field (a Link control under the hood => native search + native Advanced Search)
// pre-filled with the row's articles as pills. Source of truth = parent table
// `custom_item_tax_articles`, linked to each item row by `custom_si_row_key`.
//
// The article list is filtered to the parent group matching the line's tax template
// (ƏDV 0% -> 0% group, ƏDV-dən azadolma -> exempt group); the dialog only opens for
// those templates.

const DIALOG_CLASS = "tax-articles-dialog";
const CHILD_DOCTYPE = "Sales Invoice Tax Article";
const DISPLAY_FIELD = "custom_tax_articles_display";

const GROUP_ZERO = "ƏDV-yə 0% dərəcə ilə tutulan əməliyyatlar";
const GROUP_EXEMPT = "ƏDV-dən azad olunan əməliyyatlar";

function tax_article_group_for(template) {
	const t = (template || "").trim();
	if (t.indexOf("ƏDV 0%") === 0) return GROUP_ZERO;
	if (t.indexOf("ƏDV-dən azadolma") === 0) return GROUP_EXEMPT;
	return null;
}

if (!document.getElementById("taxmulti-style")) {
	const style = document.createElement("style");
	style.id = "taxmulti-style";
	const F = DISPLAY_FIELD;
	const D = "." + DIALOG_CLASS;
	style.textContent = [
		// grid cell: clickable, click passes through the read-only input
		'.grid-row [data-fieldname="' + F + '"]{cursor:pointer;}',
		'.grid-row [data-fieldname="' + F + '"] input,',
		'.grid-row [data-fieldname="' + F + '"] textarea,',
		'.grid-row [data-fieldname="' + F + '"] .like-disabled-input{pointer-events:none;}',

		// keep the dropdown (incl. native "Advanced Search") reachable, not clipped
		D + " .modal-body," + D + " .frappe-control," + D + " .form-group," +
			D + " .control-input-wrapper{overflow:visible!important;}",
		D + " .awesomplete > ul{max-height:260px;overflow-y:auto;z-index:1080;}",

		// ONE seamless surface: keep only the single .modal-content gradient
		D + " .modal-header," + D + " .modal-body," + D + " .modal-footer," +
			D + " .form-layout," + D + " .form-page," + D + " .form-section," +
			D + " .section-body," + D + " .form-column," + D + " .table-multiselect{" +
			"background:transparent!important;background-image:none!important;" +
			"box-shadow:none!important;border:none!important;}",

		// thin dividers under the title and above the footer
		D + " .modal-header{border-bottom:1px solid rgba(0,0,0,.15)!important;}",
		D + " .modal-footer{border-top:1px solid rgba(0,0,0,.12)!important;}",

		// trim the empty space above the field
		D + " .modal-body{padding-top:14px!important;}",

		// the search input as its own bordered field, just below the pills
		D + " .table-multiselect .awesomplete{display:block;width:100%;margin-top:8px;}",
		D + " .table-multiselect .awesomplete input{display:block;width:100%;" +
			"border:1px solid var(--border-color,#999)!important;" +
			"border-radius:var(--border-radius,6px)!important;padding:4px 8px!important;min-height:28px;}",
	].join("");
	document.head.appendChild(style);
}

frappe.ui.form.on("Sales Invoice", {
	onload(frm) {
		ensure_setup(frm);
	},
	refresh(frm) {
		ensure_setup(frm);
	},
});

frappe.ui.form.on("Sales Invoice Item", {
	// When the tax template changes, the row's already-selected articles belong to the
	// previous template's group and are no longer valid -> clear them and warn.
	item_tax_template(frm, cdt, cdn) {
		const row = locals[cdt][cdn];
		if (!row || !row.custom_si_row_key) return;

		const key = row.custom_si_row_key;
		const had = (frm.doc.custom_item_tax_articles || []).some((r) => r.parent_row === key);
		if (!had) return;

		frm.doc.custom_item_tax_articles = (frm.doc.custom_item_tax_articles || []).filter(
			(r) => r.parent_row !== key
		);
		frm.refresh_field("custom_item_tax_articles");

		const allowed = !!tax_article_group_for(row.item_tax_template);
		frappe.model.set_value(cdt, cdn, DISPLAY_FIELD, allowed ? __("Click to select") : "");

		frappe.show_alert(
			{
				message: __("Tax articles for {0} were cleared because the tax template changed.", [
					row.item_code || "#" + row.idx,
				]),
				indicator: "orange",
			},
			7
		);
	},
});

function ensure_setup(frm) {
	if (frm.__tax_articles_bound) return;
	frm.__tax_articles_bound = true;

	$(document)
		.off("mousedown.taxmulti")
		.on("mousedown.taxmulti", '[data-fieldname="' + DISPLAY_FIELD + '"]', function (ev) {
			const grid_row = $(this).closest(".grid-row").data("grid_row");
			const cdn = grid_row && grid_row.doc && grid_row.doc.name;
			if (cdn && frm.fields_dict.items && frm.fields_dict.items.grid) {
				ev.stopPropagation();
				open_tax_article_dialog(frm, cdn);
			}
		});
}

function open_tax_article_dialog(frm, cdn) {
	const row = locals["Sales Invoice Item"][cdn];
	if (!row) return;

	const group = tax_article_group_for(row.item_tax_template);
	if (!group) {
		frappe.show_alert({
			message: __(
				"Tax articles apply only to ƏDV 0% / ƏDV-dən azadolma lines. Set the item's Tax Template first."
			),
			indicator: "orange",
		});
		return;
	}

	if (!row.custom_si_row_key) {
		row.custom_si_row_key = "r" + Math.random().toString(36).slice(2, 12);
	}
	const key = row.custom_si_row_key;

	// Table MultiSelect value = array of child-row objects keyed by the link field.
	const current = (frm.doc.custom_item_tax_articles || [])
		.filter((r) => r.parent_row === key && r.tax_article)
		.map((r) => ({ tax_article: r.tax_article }));

	const d = new frappe.ui.Dialog({
		title: __("Tax Articles") + " — " + (row.item_code || "#" + row.idx),
		fields: [
			{
				fieldname: "articles",
				fieldtype: "Table MultiSelect",
				label: __("Select tax articles"),
				options: CHILD_DOCTYPE,
				get_query() {
					return { filters: { parent_tax_article: group } };
				},
			},
		],
		primary_action_label: __("Save"),
		primary_action(values) {
			const selected = Array.from(
				new Set((values.articles || []).map((r) => r.tax_article).filter(Boolean))
			);
			frm.doc.custom_item_tax_articles = (frm.doc.custom_item_tax_articles || []).filter(
				(r) => r.parent_row !== key
			);
			selected.forEach((a) => {
				const c = frm.add_child("custom_item_tax_articles");
				c.parent_row = key;
				c.tax_article = a;
			});
			const display = selected.length
				? __("{0} selected", [selected.length])
				: __("Click to select");
			frappe.model.set_value(row.doctype, row.name, DISPLAY_FIELD, display);
			frm.refresh_field("custom_item_tax_articles");
			frm.refresh_field("items");
			d.hide();
		},
	});

	d.$wrapper.addClass(DIALOG_CLASS);
	d.add_custom_action(__("Clear all"), () => d.set_value("articles", []));

	// Robust pill removal inside a Dialog. Table MultiSelect's own `.btn-remove`
	// handler does not update the field value in a dialog (it relies on a form's child
	// docs), which causes the "needs a second click / removes the wrong pills"
	// behaviour. We intercept the click in the CAPTURE phase, stop the control's broken
	// handler, and do the removal ourselves: value = current minus the clicked article.
	const fld = d.fields_dict.articles;
	fld.$wrapper[0].addEventListener(
		"click",
		function (e) {
			const btn = e.target.closest(".btn-remove");
			if (!btn) return;
			e.stopPropagation();
			const pill = btn.closest(".tb-selected-value");
			const removed = pill ? decodeURIComponent(pill.getAttribute("data-value") || "") : "";
			const remaining = (fld.get_value() || [])
				.map((r) => (typeof r === "string" ? r : r && r.tax_article))
				.filter((n) => n && n !== removed)
				.map((n) => ({ tax_article: n }));
			fld.set_value(remaining);
		},
		true
	);

	d.set_value("articles", current);
	d.show();
}
