frappe.pages["customer-records"].on_page_load = function(wrapper) {
    var page = frappe.ui.make_app_page({
        parent: wrapper,
        title: __("Customer Records"),
        single_column: true
    });

    var content = frappe.render_template("customer_records", {});
    $(page.body).append(content);

    var records = [];
    var currentIdx = -1;

    function loadRecord(idx) {
        if (idx < 0 || idx >= records.length) return;
        currentIdx = idx;
        var r = records[idx];

        $("#current-index").text(idx + 1);
        $("#total-count").text(records.length);

        // Left column
        $("#record-number").val(r.name || "");
        $("#company-name").val(r.customer_name || "");
        $("#contact-persons").val(r.contact_details || r.contact_persons || "");
        $("#email-address").val(r.email_id || "");
        $("#contact-numbers").val(r.mobile_no || r.address_phone || "");
        $("#hours-operation").val(r.hours_of_operation || "");
        $("#prospect-status").val(r.prospect_status || "");
        $("#do-not-call").prop("checked", r.do_not_call ? true : false);
        $("#comments").val(r.legacy_notes || "");
        $("#contacted-date").val(r.contacted_date || "");
        $("#follow-up-date").val(r.follow_up_date || "");

        // Right column
        $("#additional-numbers").val(r.customer_number || "");
        $("#customer-address").val(r.address_line1 || "");
        $("#city").val(r.city || "");
        $("#zip").val(r.zip || "");
        $("#last-pu-date").val(r.last_pu_date || "");

        $("#status-msg").text("Record " + (idx + 1) + " of " + records.length);
    }

    function clearForm() {
        $("input:not([type=checkbox]), textarea").val("");
        $("#do-not-call").prop("checked", false);
        $("#current-index").text(0);
        $("#total-count").text(records.length);
        $("#status-msg").text("New record");
        currentIdx = -1;
    }

    function fetchRecords() {
        frappe.call({
            method: "westech_r2.westech_r2.api.customer_records_api.get_records",
            args: { start: 0, page_length: 500 },
            freeze: true,
            freeze_message: "Loading customers...",
            callback: function(r) {
                if (r.message) {
                    records = r.message;
                    if (records.length > 0) {
                        loadRecord(0);
                    } else {
                        clearForm();
                        $("#status-msg").text("No records found");
                    }
                }
            }
        });
    }

    function saveRecord() {
        if (currentIdx < 0 || currentIdx >= records.length) {
            frappe.msgprint("No record selected to save.");
            return;
        }
        var data = {
            name: $("#record-number").val(),
            customer_name: $("#company-name").val(),
            customer_number: $("#additional-numbers").val(),
            email_id: $("#email-address").val(),
            mobile_no: $("#contact-numbers").val(),
            contact_persons: $("#contact-persons").val(),
            hours_of_operation: $("#hours-operation").val(),
            legacy_notes: $("#comments").val(),
            contacted_date: $("#contacted-date").val(),
            follow_up_date: $("#follow-up-date").val(),
            last_pu_date: $("#last-pu-date").val(),
            prospect_status: $("#prospect-status").val(),
            do_not_call: $("#do-not-call").is(":checked") ? 1 : 0,
            address_line1: $("#customer-address").val(),
            city: $("#city").val(),
            zip: $("#zip").val()
        };
        frappe.call({
            method: "westech_r2.westech_r2.api.customer_records_api.save_record",
            args: { data: JSON.stringify(data) },
            freeze: true,
            freeze_message: "Saving...",
            callback: function(r) {
                if (r.message && r.message.status === "ok") {
                    frappe.show_alert({message: "Saved successfully", indicator: "green"});
                    // Update local record
                    records[currentIdx].customer_name = data.customer_name;
                    records[currentIdx].customer_number = data.customer_number;
                    records[currentIdx].email_id = data.email_id;
                    records[currentIdx].mobile_no = data.mobile_no;
                    records[currentIdx].contact_persons = data.contact_persons;
                    records[currentIdx].hours_of_operation = data.hours_of_operation;
                    records[currentIdx].legacy_notes = data.legacy_notes;
                } else {
                    frappe.show_alert({message: "Save failed: " + (r.message ? r.message.message : "Unknown error"), indicator: "red"});
                }
            }
        });
    }

    function deleteRecord() {
        if (currentIdx < 0) return;
        var recName = $("#record-number").val();
        var recLabel = $("#company-name").val() || recName;

        frappe.confirm(
            'Delete customer "' + recLabel + '"?<br><br><strong>This cannot be undone.</strong>',
            function() {
                frappe.call({
                    method: "westech_r2.westech_r2.api.customer_records_api.delete_record",
                    args: { name: recName },
                    freeze: true,
                    freeze_message: "Deleting...",
                    callback: function(r) {
                        if (r.message && r.message.status === "ok") {
                            records.splice(currentIdx, 1);
                            if (records.length > 0) {
                                currentIdx = Math.min(currentIdx, records.length - 1);
                                loadRecord(currentIdx);
                            } else {
                                clearForm();
                            }
                            frappe.show_alert({message: "Deleted", indicator: "red"});
                        }
                    }
                });
            }
        );
    }

    function newRecord() {
        // Open a new Customer form in ERPNext
        frappe.set_route("Form", "Customer", "New");
    }

    function searchRecords() {
        var field = $("#search-field").val();
        var value = $("#search-value").val().trim();
        if (!value) {
            fetchRecords();
            return;
        }
        frappe.call({
            method: "westech_r2.westech_r2.api.customer_records_api.search_records",
            args: { field: field, value: value },
            freeze: true,
            freeze_message: "Searching...",
            callback: function(r) {
                if (r.message) {
                    records = r.message;
                    if (records.length > 0) {
                        loadRecord(0);
                        $("#status-msg").text("Found " + records.length + " record(s)");
                    } else {
                        clearForm();
                        $("#status-msg").text("No records found");
                    }
                }
            }
        });
    }

    function resetSearch() {
        $("#search-value").val("");
        fetchRecords();
    }

    // Button bindings
    $("#btn-save").click(saveRecord);
    $("#btn-delete").click(deleteRecord);
    $("#btn-new").click(newRecord);
    $("#btn-prev").click(function() { if (currentIdx > 0) loadRecord(currentIdx - 1); });
    $("#btn-next").click(function() { if (currentIdx < records.length - 1) loadRecord(currentIdx + 1); });
    $("#btn-first").click(function() { if (records.length > 0) loadRecord(0); });
    $("#btn-last").click(function() { if (records.length > 0) loadRecord(records.length - 1); });
    $("#btn-search").click(searchRecords);
    $("#btn-reset").click(resetSearch);
    $("#btn-print").click(function() { window.print(); });

    // Keyboard navigation
    $(wrapper).on("keydown", function(e) {
        if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA" || e.target.tagName === "SELECT") return;
        if (e.key === "ArrowLeft" || e.key === "PageUp") {
            e.preventDefault();
            if (currentIdx > 0) loadRecord(currentIdx - 1);
        } else if (e.key === "ArrowRight" || e.key === "PageDown") {
            e.preventDefault();
            if (currentIdx < records.length - 1) loadRecord(currentIdx + 1);
        } else if (e.key === "Home") {
            e.preventDefault();
            if (records.length > 0) loadRecord(0);
        } else if (e.key === "End") {
            e.preventDefault();
            if (records.length > 0) loadRecord(records.length - 1);
        } else if (e.key === "Enter" && e.target.id === "search-value") {
            e.preventDefault();
            searchRecords();
        }
    });

    // Load initial data
    fetchRecords();
};