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;
    var searchResults = [];

    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);
        $("#record-number").val(r.name || "");
        $("#additional-numbers").val(r.additional_numbers || "");
        $("#field-star").val(r.field_star || "");
        $("#customer-address").val(r.customer_address || "");
        $("#any-letter").val(r.any_letter || "");
        $("#city").val(r.city || "");
        $("#field-e").val(r.field_e || "");
        $("#zip").val(r.zip || "");
        $("#company-name").val(r.company_name || "");
        $("#contacted-date").val(r.contacted_date || "");
        $("#contact-persons").val(r.contact_persons || "");
        $("#follow-up-date").val(r.follow_up_date || "");
        $("#email-address").val(r.email_address || "");
        $("#last-pu-date").val(r.last_pu_date || "");
        $("#contact-numbers").val(r.contact_numbers || "");
        $("#hours-operation").val(r.hours_operation || "");
        $("#comments").val(r.comments || "");
    }

    function fetchRecords() {
        frappe.call({
            method: "westech_r2.page.customer-records.customer-records.get_records",
            callback: function(r) {
                if (r.message) {
                    records = r.message;
                    if (records.length > 0) loadRecord(0);
                    else $("#current-index").text(0);
                    $("#total-count").text(records.length);
                }
            }
        });
    }

    function saveRecord() {
        if (currentIdx < 0) return;
        var data = {
            name: $("#record-number").val(),
            additional_numbers: $("#additional-numbers").val(),
            field_star: $("#field-star").val(),
            customer_address: $("#customer-address").val(),
            any_letter: $("#any-letter").val(),
            city: $("#city").val(),
            field_e: $("#field-e").val(),
            zip: $("#zip").val(),
            company_name: $("#company-name").val(),
            contacted_date: $("#contacted-date").val(),
            contact_persons: $("#contact-persons").val(),
            follow_up_date: $("#follow-up-date").val(),
            email_address: $("#email-address").val(),
            last_pu_date: $("#last-pu-date").val(),
            contact_numbers: $("#contact-numbers").val(),
            hours_operation: $("#hours-operation").val(),
            comments: $("#comments").val()
        };
        frappe.call({
            method: "westech_r2.page.customer-records.customer-records.save_record",
            args: { data: JSON.stringify(data) },
            callback: function(r) {
                if (r.message && r.message.status === "ok") {
                    frappe.show_alert("Saved successfully");
                    records[currentIdx] = data;
                }
            }
        });
    }

    function deleteRecord() {
        if (currentIdx < 0) return;
        frappe.confirm("Delete record #" + $("#record-number").val() + "?", function() {
            frappe.call({
                method: "westech_r2.page.customer-records.customer-records.delete_record",
                args: { name: $("#record-number").val() },
                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 {
                            $("#current-index").text(0);
                            $("#total-count").text(0);
                            $("input, textarea").val("");
                        }
                        frappe.show_alert("Deleted");
                    }
                }
            });
        });
    }

    function searchRecords() {
        var field = $("#search-field").val();
        var value = $("#search-value").val().toLowerCase();
        if (!value) {
            searchResults = [];
            fetchRecords();
            return;
        }
        frappe.call({
            method: "westech_r2.page.customer-records.customer-records.search_records",
            args: { field: field, value: value },
            callback: function(r) {
                if (r.message) {
                    searchResults = r.message;
                    records = searchResults;
                    if (records.length > 0) loadRecord(0);
                    else {
                        $("#current-index").text(0);
                        $("#total-count").text(records.length);
                        $("input, textarea").val("");
                    }
                }
            }
        });
    }

    $("#btn-save").click(saveRecord);
    $("#btn-delete").click(deleteRecord);
    $("#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(function() { $("#search-value").val(""); searchResults = []; fetchRecords(); });
    $("#btn-print").click(function() { window.print(); });

    fetchRecords();
};
