// Bank Integration Excel Preset form:
//   - When a Sample File is attached, fetch its header row and use those as
//     options for the Excel Column dropdown in the child table.
//   - "Clear Sample" button removes the sample and reverts the column to free
//     text (Autocomplete with no options).
//
// The Custom Date Format field is hidden by depends_on; the parser tries a
// list of common formats automatically when the checkbox is off.

frappe.ui.form.on("Bank Integration Excel Preset", {
	refresh(frm) {
		frm.dashboard.add_comment(
			__("This doctype is deprecated. File format configuration now lives directly on the Bank Integration record, under the <b>File Format</b> tab."),
			"orange",
			true
		);

		BIPreset.applySampleHeaders(frm);

		if (frm.doc.sample_file) {
			frm.add_custom_button(__("Clear Sample"), function () {
				frappe.confirm(
					__("Remove the sample file? The Excel Column dropdown will go back to free text."),
					function () {
						frm.set_value("sample_file", null);
						BIPreset._cachedHeaders = [];
						BIPreset.setColumnOptions(frm, []);
						frm.save();
					}
				);
			});
		}
	},

	sample_file(frm) {
		BIPreset.applySampleHeaders(frm);
	},

	header_row(frm) {
		// Header row changed — if there's a sample, re-fetch headers.
		if (frm.doc.sample_file) BIPreset.applySampleHeaders(frm, /*force*/ true);
	},
});

const BIPreset = {
	_cachedHeaders: [],
	_cachedFor: null,  // "file_url::header_row" so we know when to refetch

	applySampleHeaders(frm, force) {
		if (!frm.doc.sample_file) {
			this._cachedHeaders = [];
			this._cachedFor = null;
			this.setColumnOptions(frm, []);
			return;
		}

		const key = frm.doc.sample_file + "::" + (frm.doc.header_row || 1);
		if (!force && this._cachedFor === key && this._cachedHeaders.length) {
			this.setColumnOptions(frm, this._cachedHeaders);
			return;
		}

		frappe.call({
			method: "jey_erp.bank_integration.excel_parser.parse_sample_headers",
			args: {
				file_url: frm.doc.sample_file,
				header_row: frm.doc.header_row || 1,
			},
			callback: (r) => {
				if (!r.message || !r.message.success) {
					frappe.msgprint({
						title: __("Sample File Error"),
						indicator: "red",
						message: (r.message && r.message.message) || __("Could not read sample file."),
					});
					return;
				}
				const headers = r.message.headers || [];
				this._cachedHeaders = headers;
				this._cachedFor = key;
				this.setColumnOptions(frm, headers);

				if (!headers.length) {
					frappe.show_alert({
						message: __("No headers found in row {0}. Adjust 'Header Row'.", [frm.doc.header_row || 1]),
						indicator: "orange",
					}, 5);
				} else {
					frappe.show_alert({
						message: __("{0} column header(s) loaded.", [headers.length]),
						indicator: "green",
					}, 3);
				}
			},
		});
	},

	setColumnOptions(frm, headers) {
		const grid = frm.fields_dict.column_mappings && frm.fields_dict.column_mappings.grid;
		if (!grid) return;
		// Autocomplete field accepts options as a newline-separated string.
		grid.update_docfield_property("excel_column", "options", (headers || []).join("\n"));
		grid.refresh();
	},
};
