const KB_STATUS_COLOR = {
	"Sent": "blue",
	"Confirm Wait": "yellow",
	"Success": "green",
	"Rejected": "red",
	"Cancelled": "grey",
};

function kb_show_status(frm) {
	frappe.db.get_list("Kapital Bank Payment", {
		filters: { payment_request: frm.doc.name },
		fields: ["status", "transfer_no"],
		order_by: "creation desc",
		limit: 1,
	}).then(rows => {
		if (!rows || !rows.length) return;
		const r = rows[0];
		const color = KB_STATUS_COLOR[r.status] || "grey";
		frm.page.set_indicator(__("KB: {0}", [r.status]), color);
	});
}

frappe.ui.form.on("Payment Request", {
	refresh(frm) {
		if (frm.doc.payment_request_type === "Outward" && frm.doc.docstatus === 1) {
			kb_show_status(frm);
		}

		if (frm.doc.docstatus !== 1 || frm.doc.payment_request_type !== "Outward") return;

		frm.add_custom_button(__("Send to Kapital Bank"), () => {
			frappe.confirm(__("Send this payment to Kapital Bank?"), () => {
				frm.disable_save();
				frappe.show_alert({ message: __("Sending to Kapital Bank..."), indicator: "blue" });
				frappe.call({
					method: "kapital_bank.payment_api.send_payment_request",
					args: { name: frm.doc.name },
					callback(r) {
						frm.enable_save();
						const res = r.message;
						if (!res) return;
						if (res.success) {
							frappe.show_alert({ message: __("Transfer sent successfully. Waiting for bank confirmation."), indicator: "green" }, 8);
							frm.reload_doc();
						} else if (res.errors && res.errors.length) {
							frappe.msgprint({
								title: __("Cannot Send — Validation Failed"),
								indicator: "red",
								message: "<ul>" + res.errors.map(e => `<li>${e}</li>`).join("") + "</ul>",
							});
						} else {
							frappe.msgprint({
								title: __("Bank Error"),
								indicator: "red",
								message: res.message || __("Unknown error"),
							});
						}
					},
				});
			});
		}, __("Kapital Bank"));

		frm.add_custom_button(__("Check Status"), () => {
			frappe.show_alert({ message: __("Checking transfer status..."), indicator: "blue" });
			frappe.call({
				method: "kapital_bank.payment_api.check_payment_status",
				args: { name: frm.doc.name },
				callback(r) {
					const res = r.message;
					if (!res) return;
					if (res.message) {
						frappe.show_alert({ message: res.message, indicator: "grey" }, 5);
					} else if (res.updated > 0) {
						frappe.show_alert({ message: __("Status updated successfully."), indicator: "green" }, 5);
					} else {
						frappe.show_alert({ message: __("No status changes from bank."), indicator: "grey" }, 5);
					}
					frm.reload_doc();
				},
			});
		}, __("Kapital Bank"));

		frm.add_custom_button(__("Cancel Bank Transfer"), () => {
			frappe.confirm(__("Cancel the pending bank transfer? This cannot be undone."), () => {
				frappe.show_alert({ message: __("Cancelling..."), indicator: "blue" });
				frappe.call({
					method: "kapital_bank.payment_api.cancel_payment_request",
					args: { name: frm.doc.name },
					callback(r) {
						const res = r.message;
						if (!res) return;
						if (res.success && res.cancelled > 0) {
							frappe.show_alert({ message: __("Bank transfer cancelled successfully."), indicator: "green" }, 6);
							frm.reload_doc();
						} else if (res.errors && res.errors.length) {
							frappe.msgprint({
								title: __("Cancel Failed"),
								indicator: "red",
								message: "<ul>" + res.errors.map(e => `<li>${e}</li>`).join("") + "</ul>",
							});
						} else if (res.message) {
							frappe.show_alert({ message: res.message, indicator: "grey" }, 5);
						} else {
							frappe.msgprint({
								title: __("Cancel Failed"),
								indicator: "red",
								message: __("Unknown error"),
							});
						}
					},
				});
			});
		}, __("Kapital Bank"));
	},
});
