frappe.listview_settings["Currency Exchange"] = {
    onload: function (listview) {
        listview.page.add_inner_button(__("Import CBAR Rates"), function () {
            // Fetch available currencies from CBAR first, then show dialog
            frappe.call({
                method: "jey_erp.cbar_exchange.get_cbar_currencies",
                callback: function (r) {
                    const available = r.message || [];
                    _show_import_dialog(available);
                }
            });
        });
    }
};

function _show_import_dialog(available_currencies) {
    const today = frappe.datetime.get_today();

    // Build lookup for fast filtering in get_data
    const currency_set = new Set(available_currencies);

    const d = new frappe.ui.Dialog({
        title: __("Import CBAR Exchange Rates"),
        fields: [
            { fieldname: "from_date", fieldtype: "Date", label: __("From Date"), reqd: 1, default: today },
            { fieldname: "to_date",   fieldtype: "Date", label: __("To Date"),   reqd: 1, default: today },
            {
                fieldname: "currencies",
                fieldtype: "MultiSelectList",
                label: __("Currencies"),
                reqd: 1,
                get_data: function (txt) {
                    return available_currencies
                        .filter(c => !txt || c.toLowerCase().includes(txt.toLowerCase()))
                        .map(c => ({ value: c, description: c }));
                }
            },
            {
                fieldname: "note", fieldtype: "HTML",
                options: `<p class="text-muted small">${__("Rates are loaded from cbar.az for each day in the range. Existing records will be updated.")}</p>`
            }
        ],
        primary_action_label: __("Import"),
        primary_action: function (values) {
            const currencies = values.currencies;
            if (!currencies || !currencies.length) {
                frappe.msgprint(__("Please select at least one currency."));
                return;
            }

            d.hide();

            frappe.realtime.off("cbar_import_progress");
            frappe.realtime.off("cbar_import_complete");

            frappe.realtime.on("cbar_import_progress", function (data) {
                frappe.show_progress(
                    __("Importing CBAR Rates"),
                    data.current,
                    data.total,
                    __("Loading {0} ({1} of {2})", [data.date, data.current, data.total])
                );
            });

            frappe.realtime.on("cbar_import_complete", function (data) {
                frappe.realtime.off("cbar_import_progress");
                frappe.realtime.off("cbar_import_complete");
                frappe.hide_progress();

                const { created, updated, skipped_dates } = data;
                let msg = `<b>${__("Import complete")}</b><br>${__("Created")}: ${created}<br>${__("Updated")}: ${updated}`;
                if (skipped_dates && skipped_dates.length)
                    msg += `<br><span class="text-danger">${__("Failed dates")}: ${skipped_dates.join(", ")}</span>`;
                frappe.msgprint({
                    title: __("CBAR Import Result"),
                    message: msg,
                    indicator: skipped_dates && skipped_dates.length ? "orange" : "green"
                });
                cur_list && cur_list.refresh();
            });

            frappe.call({
                method: "jey_erp.cbar_exchange.fetch_cbar_rates",
                args: {
                    from_date: values.from_date,
                    to_date: values.to_date,
                    currencies: currencies
                },
                error: function () {
                    frappe.realtime.off("cbar_import_progress");
                    frappe.realtime.off("cbar_import_complete");
                    frappe.hide_progress();
                }
            });
        }
    });

    d.show();
    // Default: USD only
    d.set_value("currencies", ["USD"]);
}
