const KBMapping = {};

KBMapping.init = function(dialog, txns) {
	const $container = dialog.$wrapper.find('.kb-bt-txn-table').closest('div');
	if ($container.length === 0) return;

	// Search input + button row
	const $toolbar = $(`
		<div class="kb-mapping-toolbar" style="display: flex; gap: 10px; align-items: center; margin-bottom: 10px;">
			<input type="text" class="form-control kb-mapping-search"
				placeholder="${__('Search by purpose...')}"
				style="flex: 1; max-width: 300px;">
			<button class="btn btn-primary btn-sm kb-mapping-btn" style="display: none; white-space: nowrap;">
				${__('Create Purpose Mapping')}
			</button>
		</div>
	`);
	$container.prepend($toolbar);

	const $searchInput = $toolbar.find('.kb-mapping-search');
	const $mappingBtn = $toolbar.find('.kb-mapping-btn');

	// Search: filter rows by purpose column (8th td, index 7)
	$searchInput.on('input', function() {
		const query = $(this).val().toLowerCase();
		dialog.$wrapper.find('.kb-bt-txn-table tbody tr').each(function() {
			const purposeText = $(this).find('td').eq(7).text().toLowerCase();
			$(this).toggle(purposeText.indexOf(query) !== -1);
		});
	});

	// Toggle mapping button visibility based on checked rows
	function toggleMappingBtn() {
		const anyChecked = dialog.$wrapper.find('.kb-bt-select-txn:checked').length > 0;
		$mappingBtn.toggle(anyChecked);
	}

	dialog.$wrapper.on('change', '.kb-bt-select-txn, .kb-bt-select-all-txns', toggleMappingBtn);

	// Button click -> show mapping dialog
	$mappingBtn.on('click', function() {
		KBMapping.showMappingDialog(dialog, txns);
	});
};

KBMapping.showMappingDialog = function(parentDialog, txns) {
	// Collect checked transactions
	const selectedTxns = [];
	parentDialog.$wrapper.find('.kb-bt-select-txn:checked').each(function() {
		const idx = $(this).data('idx');
		selectedTxns.push(txns[idx]);
	});

	if (selectedTxns.length === 0) {
		frappe.msgprint({ title: __('Warning'), indicator: 'orange', message: __('No transactions selected') });
		return;
	}

	// Build unique purposes: key = "purpose|payment_type"
	const purposeMap = new Map();
	let skippedCount = 0;

	selectedTxns.forEach(function(txn) {
		const purpose = (txn.purpose || '').trim();
		if (!purpose) {
			skippedCount++;
			return;
		}
		const paymentType = txn.drcr === 'D' ? 'Pay' : 'Receive';
		const key = purpose + '|' + paymentType;
		if (purposeMap.has(key)) {
			purposeMap.get(key).count++;
		} else {
			purposeMap.set(key, { purpose: purpose, payment_type: paymentType, count: 1 });
		}
	});

	if (purposeMap.size === 0 && skippedCount > 0) {
		frappe.msgprint({
			title: __('No Purposes'),
			indicator: 'orange',
			message: __('All selected transactions have no purpose text.'),
		});
		return;
	}

	// Preview table
	let previewHtml = '<div style="max-height: 300px; overflow-y: auto; margin-bottom: 15px;">';
	previewHtml += '<table class="table table-bordered" style="width: 100%;">';
	previewHtml += '<thead><tr>' +
		'<th>' + __('Purpose') + '</th>' +
		'<th style="width: 100px;">' + __('Type') + '</th>' +
		'<th style="width: 80px; text-align: center;">' + __('Txns') + '</th>' +
		'</tr></thead><tbody>';

	purposeMap.forEach(function(entry) {
		const typeLabel = entry.payment_type === 'Pay'
			? '<span class="label label-danger">Pay</span>'
			: '<span class="label label-success">Receive</span>';
		previewHtml += '<tr>' +
			'<td style="word-break: break-word; font-size: 0.9em;">' + entry.purpose + '</td>' +
			'<td>' + typeLabel + '</td>' +
			'<td style="text-align: center;">' + entry.count + '</td>' +
			'</tr>';
	});

	previewHtml += '</tbody></table></div>';

	if (skippedCount > 0) {
		previewHtml += '<div class="alert alert-warning">' +
			__('{0} transaction(s) skipped — no purpose text.', [skippedCount]) +
			'</div>';
	}

	const d = new frappe.ui.Dialog({
		title: __('Create Purpose Mappings') + ' (' + purposeMap.size + ')',
		size: 'large',
		fields: [
			{
				fieldname: 'preview_html',
				fieldtype: 'HTML',
				options: previewHtml,
			},
			{ fieldname: 'sec_accounts', fieldtype: 'Section Break', label: __('GL Accounts') },
			{
				fieldname: 'paid_from',
				fieldtype: 'Link',
				options: 'Account',
				label: __('Paid From (Account)'),
				reqd: 1,
			},
			{ fieldname: 'col_break', fieldtype: 'Column Break' },
			{
				fieldname: 'paid_to',
				fieldtype: 'Link',
				options: 'Account',
				label: __('Paid To (Account)'),
				reqd: 1,
			},
		],
		primary_action_label: __('Create Mappings'),
		primary_action: function() {
			const values = d.get_values();
			if (!values) return;
			KBMapping._submitMappings(d, selectedTxns, values.paid_from, values.paid_to);
		},
	});

	d.show();
};

KBMapping._submitMappings = function(dialog, txns, paid_from, paid_to) {
	dialog.disable_primary_action();

	frappe.call({
		method: 'kapital_bank.mapping.create_purpose_mappings',
		args: {
			transactions: JSON.stringify(txns),
			paid_from: paid_from,
			paid_to: paid_to,
		},
		callback: function(r) {
			dialog.enable_primary_action();

			if (!r.message || !r.message.success) {
				frappe.msgprint({
					title: __('Error'),
					indicator: 'red',
					message: r.message ? r.message.message : __('Unknown error'),
				});
				return;
			}

			dialog.hide();

			const res = r.message;
			let parts = [];
			if (res.created) parts.push(__('Created: {0}', [res.created]));
			if (res.already_mapped) parts.push(__('Already mapped: {0}', [res.already_mapped]));
			if (res.skipped_no_data) parts.push(__('Skipped (no purpose): {0}', [res.skipped_no_data]));

			frappe.show_alert({
				message: parts.join(' &bull; ') || __('No changes'),
				indicator: res.created > 0 ? 'green' : 'blue',
			}, 5);
		},
		error: function() {
			dialog.enable_primary_action();
			frappe.msgprint({
				title: __('Error'),
				indicator: 'red',
				message: __('Network error creating mappings'),
			});
		},
	});
};
