// Buttons on Bank Statement Importer form: matching, creation, add unmapped
// Mirrors the kapital_bank_settings.js layout for familiarity.

frappe.ui.form.on('Bank Statement Importer', {
	setup(frm) {
		// Customer/Supplier Group and Territory must be leaf (non-group) nodes —
		// don't let group nodes be picked here or in the mapping child tables.
		const leaf = () => ({ filters: { is_group: 0 } });
		frm.set_query('default_customer_group', leaf);
		frm.set_query('default_supplier_group', leaf);
		frm.set_query('default_territory', leaf);
		frm.set_query('customer_group', 'customer_mappings', leaf);
		frm.set_query('territory', 'customer_mappings', leaf);
		frm.set_query('supplier_group', 'supplier_mappings', leaf);
		frm.set_query('cost_center', 'transaction_mappings', leaf);
	},

	refresh(frm) {
		BIFileFormat.applySampleHeaders(frm);

		if (frm.is_new()) return;

		// Replace the standard Menu → Delete with a cascading version. The
		// stock action would just error out on the link-check (registry rows
		// + Bank Account dynamic-link) and leave the user stuck.
		// frm.savetrash() is what the Menu Delete item ultimately calls.
		frm.savetrash = () => BSICascadeDelete.run(frm);

		// === Load Data (file-based, registry-only) ===
		frm.add_custom_button(__('Load Data'), () => {
			_show_load_data_dialog(frm);
		});

		// === Customers group ===
		frm.add_custom_button(__('Match customers by similar name'), () => {
			_safe(frm, () => _call(frm, 'jey_erp.bank_integration.matching.match_similar_customers',
				{ bank_integration: frm.doc.name },
				r => frappe.show_alert({
					message: __('Matched: {0} of {1}', [r.matched_count, r.total_processed]),
					indicator: 'green',
				}, 5),
			));
		}, __('Customers'));

		frm.add_custom_button(__('Create matching customers'), () => {
			_safe(frm, () => _call(frm, 'jey_erp.bank_integration.creation.create_unmapped_customers',
				{ bank_integration: frm.doc.name },
				r => frappe.show_alert({
					message: __('Created: {0}', [r.created_count]),
					indicator: 'green',
				}, 5),
			));
		}, __('Customers'));

		frm.add_custom_button(__('Add unmapped customers'), () => {
			_safe(frm, () => _call(frm, 'jey_erp.bank_integration.creation.add_unmapped_to_table',
				{ bank_integration: frm.doc.name, table: 'customer_mappings' },
				r => frappe.show_alert({
					message: __('Added: {0}', [r.added_count]),
					indicator: 'blue',
				}, 5),
			));
		}, __('Customers'));

		// === Suppliers group ===
		frm.add_custom_button(__('Match suppliers by similar name'), () => {
			_safe(frm, () => _call(frm, 'jey_erp.bank_integration.matching.match_similar_suppliers',
				{ bank_integration: frm.doc.name },
				r => frappe.show_alert({
					message: __('Matched: {0} of {1}', [r.matched_count, r.total_processed]),
					indicator: 'green',
				}, 5),
			));
		}, __('Suppliers'));

		frm.add_custom_button(__('Create matching suppliers'), () => {
			_safe(frm, () => _call(frm, 'jey_erp.bank_integration.creation.create_unmapped_suppliers',
				{ bank_integration: frm.doc.name },
				r => frappe.show_alert({
					message: __('Created: {0}', [r.created_count]),
					indicator: 'green',
				}, 5),
			));
		}, __('Suppliers'));

		frm.add_custom_button(__('Add unmapped suppliers'), () => {
			_safe(frm, () => _call(frm, 'jey_erp.bank_integration.creation.add_unmapped_to_table',
				{ bank_integration: frm.doc.name, table: 'supplier_mappings' },
				r => frappe.show_alert({
					message: __('Added: {0}', [r.added_count]),
					indicator: 'blue',
				}, 5),
			));
		}, __('Suppliers'));

		// === Purposes group ===
		frm.add_custom_button(__('Add unmapped purposes'), () => {
			_safe(frm, () => _call(frm, 'jey_erp.bank_integration.creation.add_unmapped_to_table',
				{ bank_integration: frm.doc.name, table: 'transaction_mappings' },
				r => frappe.show_alert({
					message: __('Added: {0}', [r.added_count]),
					indicator: 'blue',
				}, 5),
			));
		}, __('Purposes'));

		// === Data tab rendering ===
		_bi_load_data_tabs(frm);
	},

	sample_file(frm) {
		BIFileFormat.onSampleFileChange(frm);
	},

	header_row(frm) {
		if (frm.doc.sample_file) BIFileFormat.applySampleHeaders(frm, /*force*/ true);
	},

	preview_sample_btn(frm) {
		BIFileFormat.showPreview(frm);
	},
});

// ─── File Format helpers ─────────────────────────────────────────────────────
// Mirrors what bank_integration_excel_preset.js used to do, but on the merged
// File Format tab of the Bank Statement Importer form: a Sample File attachment turns
// the Excel Column field in the column_mappings grid into a dropdown of real
// header strings, so users don't have to type them.

const BIFileFormat = {
	_cachedHeaders: [],
	_cachedFor: null,

	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.show_alert({
						message: (r.message && r.message.message) || __('Could not read sample file.'),
						indicator: 'red',
					}, 5);
					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);
				}
			},
		});
	},

	// Called when the user attaches / replaces / clears the Sample Excel File.
	// Refresh the Excel Column dropdown, then either auto-detect silently
	// (empty table) or ask before overwriting an existing mapping (re-upload).
	onSampleFileChange(frm) {
		this.applySampleHeaders(frm, /*force*/ true);
		if (!frm.doc.sample_file) return;

		const hasRows = (frm.doc.column_mappings || []).some(r => r.excel_column || r.standard_field);
		if (!hasRows) {
			this.autoDetect(frm, /*silent*/ true);
			return;
		}
		frappe.confirm(
			__('Re-run auto-detect and replace the existing {0} Column Mapping row(s)?', [
				frm.doc.column_mappings.length,
			]),
			() => this.autoDetect(frm, /*silent*/ true),
		);
	},

	setColumnOptions(frm, headers) {
		const grid = frm.fields_dict.column_mappings && frm.fields_dict.column_mappings.grid;
		if (!grid) return;
		grid.update_docfield_property('excel_column', 'options', (headers || []).join('\n'));
		grid.refresh();
	},

	showPreview(frm) {
		if (!frm.doc.sample_file) {
			frappe.msgprint(__('Upload a Sample Excel File first.'));
			return;
		}
		frappe.call({
			method: 'jey_erp.bank_integration.excel_parser.parse_sample_preview',
			args: {
				file_url: frm.doc.sample_file,
				header_row: frm.doc.header_row || 1,
				max_rows: 20,
			},
			callback: (r) => {
				if (!r.message || !r.message.success) {
					frappe.msgprint({
						title: __('Preview Error'),
						indicator: 'red',
						message: (r.message && r.message.message) || __('Could not read sample file.'),
					});
					return;
				}
				const headers = r.message.headers || [];
				const rows = r.message.rows || [];
				const esc = frappe.utils.escape_html;

				if (!headers.length) {
					frappe.msgprint({
						title: __('Empty Header Row'),
						indicator: 'orange',
						message: __("No headers found in row {0}. Adjust 'Header Row' and try again.", [frm.doc.header_row || 1]),
					});
					return;
				}

				// Build a header → standard_field map from the current grid so
				// the preview can show which columns are mapped.
				const mappedBy = {};
				(frm.doc.column_mappings || []).forEach(r => {
					if (r.excel_column && r.standard_field) {
						mappedBy[r.excel_column.trim().toLowerCase()] = r.standard_field;
					}
				});

				let html = '<div style="max-height: 500px; overflow:auto;">';
				html += '<div class="text-muted small" style="margin-bottom:8px;">' +
					__('Showing first {0} data row(s) starting after Header Row {1}.',
						[rows.length, r.message.header_row]) + '</div>';
				html += '<table class="table table-bordered" style="font-size:12px; white-space:nowrap;">';
				html += '<thead style="position:sticky; top:0; background:var(--bg-color); z-index:1;">';
				html += '<tr>';
				headers.forEach(h => {
					const std = mappedBy[h.trim().toLowerCase()];
					const badge = std
						? ` <span class="label label-success" style="font-size:9px;">${esc(std)}</span>`
						: ` <span class="label label-default" style="font-size:9px;">${__('unmapped')}</span>`;
					html += `<th>${esc(h)}${badge}</th>`;
				});
				html += '</tr></thead><tbody>';
				rows.forEach(row => {
					html += '<tr>';
					row.forEach(cell => {
						html += `<td>${esc(cell)}</td>`;
					});
					html += '</tr>';
				});
				html += '</tbody></table></div>';

				const d = new frappe.ui.Dialog({
					title: __('Sample File Preview'),
					size: 'extra-large',
					fields: [{ fieldname: 'preview_html', fieldtype: 'HTML', options: html }],
					primary_action_label: __('Close'),
					primary_action() { d.hide(); },
				});
				d.$wrapper.find('.modal-dialog').css({ 'max-width': '95%', 'width': '95%' });
				d.show();
			},
		});
	},

	autoDetect(frm, silent) {
		if (!frm.doc.sample_file) return;
		frappe.call({
			method: 'jey_erp.bank_integration.excel_parser.auto_detect_column_mappings',
			args: {
				file_url: frm.doc.sample_file,
				header_row: frm.doc.header_row || 1,
			},
			callback: (r) => {
				if (!r.message || !r.message.success) {
					frappe.show_alert({
						message: (r.message && r.message.message) || __('Could not read sample file.'),
						indicator: 'red',
					}, 5);
					return;
				}
				const mappings = r.message.mappings || [];
				if (!mappings.length) {
					frappe.show_alert({
						message: __("No headers found in row {0}. Adjust 'Header Row'.", [frm.doc.header_row || 1]),
						indicator: 'orange',
					}, 5);
					return;
				}
				frm.clear_table('column_mappings');
				mappings.forEach(m => {
					const row = frm.add_child('column_mappings');
					row.excel_column = m.excel_column;
					row.standard_field = m.standard_field || '';
				});
				frm.refresh_field('column_mappings');
				frm.dirty();

				const matched = r.message.matched_count || 0;
				const total = r.message.total_headers || mappings.length;
				const indicator = matched === total ? 'green' : (matched > 0 ? 'orange' : 'red');
				frappe.show_alert({
					message: __('Auto-mapped {0} of {1} columns.', [matched, total]),
					indicator,
				}, silent ? 4 : 6);
			},
		});
	},
};

function _safe(frm, action) {
	if (frm.is_dirty()) {
		frappe.confirm(
			__('Document contains unsaved changes. Save before performing the operation?'),
			() => frm.save().then(action),
			() => frappe.show_alert({ message: __('Operation canceled. Save first.'), indicator: 'red' }, 5),
		);
	} else {
		action();
	}
}

function _call(frm, method, args, onSuccess) {
	frappe.show_alert({ message: __('Working...'), indicator: 'blue' });
	frappe.call({
		method,
		args,
		callback(r) {
			if (!r.message) return;
			if (r.message.success === false) {
				frappe.msgprint({
					title: __('Error'),
					indicator: 'red',
					message: r.message.message || __('Unknown error'),
				});
				return;
			}
			onSuccess(r.message);
			frm.reload_doc();
		},
	});
}

function _show_load_data_dialog(frm) {
	if (!frm.doc.column_mappings || !frm.doc.column_mappings.length) {
		frappe.msgprint({
			title: __('No Column Mappings'),
			indicator: 'orange',
			message: __('Open the <b>File Format</b> tab first and map Excel columns to Standard Fields.'),
		});
		return;
	}
	const d = new frappe.ui.Dialog({
		title: __('Load Data from Excel'),
		fields: [
			{
				fieldname: 'file_url',
				fieldtype: 'Attach',
				label: __('Excel File'),
				reqd: 1,
				description: __('Format is read from the File Format tab on this Bank Statement Importer.'),
			},
			{ fieldname: 'sec_what', fieldtype: 'Section Break', label: __('What to load') },
			{
				fieldname: 'load_customers',
				fieldtype: 'Check',
				label: __('Customers (incoming counterparties)'),
				default: 1,
			},
			{
				fieldname: 'load_suppliers',
				fieldtype: 'Check',
				label: __('Suppliers (outgoing counterparties)'),
				default: 1,
			},
			{
				fieldname: 'load_purposes',
				fieldtype: 'Check',
				label: __('Purpose keywords'),
				default: 1,
			},
		],
		primary_action_label: __('Load'),
		primary_action(values) {
			if (!values.load_customers && !values.load_suppliers && !values.load_purposes) {
				frappe.msgprint({
					title: __('Nothing Selected'),
					indicator: 'orange',
					message: __('Pick at least one type to load.'),
				});
				return;
			}
			d.disable_primary_action();
			frappe.call({
				method: 'jey_erp.bank_integration.import_api.load_registries_from_excel',
				args: {
					file_url: values.file_url,
					bank_integration: frm.doc.name,
					load_customers: values.load_customers ? 1 : 0,
					load_suppliers: values.load_suppliers ? 1 : 0,
					load_purposes: values.load_purposes ? 1 : 0,
				},
				callback(r) {
					d.enable_primary_action();
					if (!r.message || r.message.success === false) {
						frappe.msgprint({
							title: __('Error'),
							indicator: 'red',
							message: (r.message && r.message.message) || __('Unknown error'),
						});
						return;
					}
					d.hide();
					const res = r.message;
					const droppedDate = res.dropped_date || 0;
					const droppedAmount = res.dropped_amount || 0;
					const droppedDirection = res.dropped_direction || 0;
					const unknownDirections = res.unknown_directions || [];
					let msg = __('From {0} rows — new customers: {1}, suppliers: {2}, purposes: {3}',
						[res.total_rows, res.new_customers, res.new_suppliers, res.new_purposes]);
					if (droppedDate > 0) {
						msg += '<br><br><span class="text-warning">' +
							__("Note: {0} row(s) had unparseable dates and were skipped. Enable 'Use Custom Date Format' in the File Format tab if your bank uses an unusual date format.",
								[droppedDate]) +
							'</span>';
					}
					if (droppedDirection > 0) {
						const sample = unknownDirections.map(frappe.utils.escape_html).join(', ') || '?';
						msg += '<br><br><span class="text-warning">' +
							__('Also skipped {0} row(s) with unknown direction values: <code>{1}</code>. Add them to Debit/Credit Values in the File Format tab.',
								[droppedDirection, sample]) +
							'</span>';
					}
					if (droppedAmount > 0) {
						msg += '<br><span class="text-muted">' +
							__('Also skipped {0} row(s) with missing/zero amount.', [droppedAmount]) +
							'</span>';
					}
					frappe.msgprint({
						title: __('Data Loaded'),
						indicator: (droppedDate > 0 || droppedDirection > 0) ? 'orange' : 'green',
						message: msg,
					});
					frm.reload_doc();
				},
				error() {
					d.enable_primary_action();
					frappe.msgprint({ title: __('Error'), indicator: 'red', message: __('Network error') });
				},
			});
		},
	});
	d.show();
}

// ═══════════════════════════════════════════════════════════════════════════════
// DATA TAB — registry overviews (Accounts / Customers / Suppliers / Purposes)
// ═══════════════════════════════════════════════════════════════════════════════

function _bi_load_data_tabs(frm) {
	const name = frm.doc.name;
	_bi_load_tab(name, 'customers', 'bi-customers-container', _bi_render_customers);
	_bi_load_tab(name, 'suppliers', 'bi-suppliers-container', _bi_render_suppliers);
	_bi_load_tab(name, 'purposes', 'bi-purposes-container', _bi_render_purposes);
}

function _bi_load_tab(bank_integration, data_type, container_id, renderer) {
	$('#' + container_id).html(_bi_loading_html());
	frappe.call({
		method: 'jey_erp.bank_integration.import_api.get_bi_reference_data_list',
		args: { bank_integration, data_type, limit: 100, offset: 0 },
		callback(r) {
			if (r.message && r.message.success) {
				renderer(r.message.data, r.message.total_count, () => _bi_load_tab(bank_integration, data_type, container_id, renderer));
			} else {
				$('#' + container_id).html(_bi_error_html(r.message ? r.message.message : __('Unknown error')));
			}
		},
		error() { $('#' + container_id).html(_bi_error_html(__('Network error'))); },
	});
}

function _bi_render_customers(rows, total, reload) {
	let html = _bi_list_header(__('Customers'), total, 'bi-refresh-customers');
	if (rows && rows.length) {
		html += `<table class="table table-bordered" style="font-size:13px;">
			<thead class="grid-heading-row"><tr>
				<th>${__('Customer Name')}</th><th>${__('Tax ID (VOEN)')}</th><th>${__('IBAN')}</th>
				<th>${__('Status')}</th><th>${__('Mapped To')}</th><th>${__('Created')}</th>
			</tr></thead><tbody>`;
		rows.forEach(c => {
			const pill = c.status === 'Mapped' ? 'green' : 'red';
			const mapped = c.mapped_customer ? `<a href="/app/customer/${encodeURIComponent(c.mapped_customer)}">${c.mapped_customer}</a>` : '-';
			const created = c.creation ? frappe.datetime.str_to_user(c.creation) : '-';
			html += `<tr>
				<td><a href="/app/bank-integration-customer/${encodeURIComponent(c.name)}">${frappe.utils.escape_html(c.customer_name)}</a></td>
				<td>${c.tax_id || '-'}</td><td>${c.iban || '-'}</td>
				<td><span class="indicator-pill ${pill}">${__(c.status)}</span></td>
				<td>${mapped}</td><td>${created}</td></tr>`;
		});
		html += '</tbody></table>';
	} else {
		html += _bi_empty_state(__('No customers registered yet. Import a statement (with "Also load counterparties & purposes") or use "Load Data".'));
	}
	$('#bi-customers-container').html(html);
	$('#bi-refresh-customers').on('click', reload);
}

function _bi_render_suppliers(rows, total, reload) {
	let html = _bi_list_header(__('Suppliers'), total, 'bi-refresh-suppliers');
	if (rows && rows.length) {
		html += `<table class="table table-bordered" style="font-size:13px;">
			<thead class="grid-heading-row"><tr>
				<th>${__('Supplier Name')}</th><th>${__('Tax ID (VOEN)')}</th><th>${__('IBAN')}</th>
				<th>${__('Status')}</th><th>${__('Mapped To')}</th><th>${__('Created')}</th>
			</tr></thead><tbody>`;
		rows.forEach(s => {
			const pill = s.status === 'Mapped' ? 'green' : 'red';
			const mapped = s.mapped_supplier ? `<a href="/app/supplier/${encodeURIComponent(s.mapped_supplier)}">${s.mapped_supplier}</a>` : '-';
			const created = s.creation ? frappe.datetime.str_to_user(s.creation) : '-';
			html += `<tr>
				<td><a href="/app/bank-integration-supplier/${encodeURIComponent(s.name)}">${frappe.utils.escape_html(s.supplier_name)}</a></td>
				<td>${s.tax_id || '-'}</td><td>${s.iban || '-'}</td>
				<td><span class="indicator-pill ${pill}">${__(s.status)}</span></td>
				<td>${mapped}</td><td>${created}</td></tr>`;
		});
		html += '</tbody></table>';
	} else {
		html += _bi_empty_state(__('No suppliers registered yet.'));
	}
	$('#bi-suppliers-container').html(html);
	$('#bi-refresh-suppliers').on('click', reload);
}

function _bi_render_purposes(rows, total, reload) {
	let html = _bi_list_header(__('Purposes'), total, 'bi-refresh-purposes');
	if (rows && rows.length) {
		html += `<table class="table table-bordered" style="font-size:13px;">
			<thead class="grid-heading-row"><tr>
				<th>${__('Purpose Keyword')}</th><th>${__('Direction')}</th><th>${__('Status')}</th>
			</tr></thead><tbody>`;
		rows.forEach(p => {
			const pill = p.status === 'Mapped' ? 'green' : 'red';
			html += `<tr>
				<td><a href="/app/bank-integration-purpose/${encodeURIComponent(p.name)}">${frappe.utils.escape_html(p.purpose_keyword || '')}</a></td>
				<td>${__(p.direction || '-')}</td>
				<td><span class="indicator-pill ${pill}">${__(p.status)}</span></td></tr>`;
		});
		html += '</tbody></table>';
	} else {
		html += _bi_empty_state(__('No purpose keywords registered yet.'));
	}
	$('#bi-purposes-container').html(html);
	$('#bi-refresh-purposes').on('click', reload);
}

function _bi_loading_html() {
	return `<div class="text-center text-muted" style="padding:20px;"><i class="fa fa-spinner fa-spin"></i> ${__('Loading...')}</div>`;
}

function _bi_empty_state(msg) {
	return `<div class="text-center text-muted" style="padding:30px;"><p>${msg}</p></div>`;
}

function _bi_error_html(msg) {
	return `<div class="alert alert-warning"><p>${__('Error loading data')}: ${frappe.utils.escape_html(String(msg))}</p></div>`;
}

function _bi_list_header(label, total, refresh_id) {
	return `<div class="clearfix" style="margin-bottom:10px;">
		<div class="pull-left"><h6 class="text-muted">${label} (${total} ${__('total')})</h6></div>
		<div class="pull-right"><button class="btn btn-xs btn-default" id="${refresh_id}">
			<i class="octicon octicon-sync"></i> ${__('Refresh')}</button></div>
	</div>`;
}

// ═══════════════════════════════════════════════════════════════════════════════
// CASCADE DELETE — replace Menu → Delete with a confirm dialog that explains
// what registry rows and Bank Account links will be cleaned up along with
// this importer.
// ═══════════════════════════════════════════════════════════════════════════════

const BSICascadeDelete = {
	run(frm) {
		if (frm.is_new()) return;
		frappe.call({
			method: 'jey_erp.bank_integration.cascade_delete.get_dependents',
			args: { name: frm.doc.name },
			callback: (r) => {
				if (!r.message) return;
				this._showConfirm(frm, r.message);
			},
		});
	},

	_showConfirm(frm, counts) {
		const items = [
			[__('Customers (registry)'), counts['Bank Integration Customer'] || 0],
			[__('Suppliers (registry)'), counts['Bank Integration Supplier'] || 0],
			[__('Purposes (registry)'), counts['Bank Integration Purpose'] || 0],
			[__('Bank Accounts (will be unlinked, not deleted)'), counts['Bank Account'] || 0],
		];
		const total = items.reduce((s, [, n]) => s + n, 0);
		const rows = items
			.filter(([, n]) => n > 0)
			.map(([label, n]) => `<li>${frappe.utils.escape_html(label)}: <b>${n}</b></li>`)
			.join('');

		const body = total === 0
			? `<p>${__('No dependent records — deleting this importer is safe.')}</p>`
			: `<p>${__('Deleting <b>{0}</b> will also affect:', [frappe.utils.escape_html(frm.doc.name)])}</p>
			   <ul style="margin-left:18px;">${rows}</ul>
			   <p>${__('Registry rows will be <b>deleted</b>. Bank Accounts will only have their Bank Statement Importer link cleared — the accounts themselves stay.')}</p>
			   <p class="text-danger"><b>${__('This cannot be undone.')}</b></p>`;

		const d = new frappe.ui.Dialog({
			title: __('Delete Bank Statement Importer?'),
			fields: [{ fieldname: 'body', fieldtype: 'HTML', options: body }],
			primary_action_label: __('Delete Everything'),
			primary_action: () => {
				d.disable_primary_action();
				this._doDelete(frm.doc.name).then(() => {
					d.hide();
					frappe.set_route('List', 'Bank Statement Importer');
				}).catch(() => {
					d.enable_primary_action();
				});
			},
			secondary_action_label: __('Cancel'),
			secondary_action: () => d.hide(),
		});
		// Primary button red since this is destructive.
		d.show();
		d.get_primary_btn().removeClass('btn-primary').addClass('btn-danger');
	},

	_doDelete(name) {
		return new Promise((resolve, reject) => {
			frappe.call({
				method: 'jey_erp.bank_integration.cascade_delete.cascade_delete',
				args: { name },
				freeze: true,
				freeze_message: __('Deleting…'),
				callback: (r) => {
					if (!r.message || r.message.success === false) {
						frappe.msgprint({
							title: __('Delete Failed'),
							indicator: 'red',
							message: (r.message && r.message.message) || __('Unknown error'),
						});
						reject();
						return;
					}
					frappe.show_alert({ message: __('Deleted.'), indicator: 'green' }, 4);
					resolve();
				},
				error: reject,
			});
		});
	},
};
