frappe.pages["customer-intake"].on_page_load = function(wrapper) {
    var page = frappe.ui.make_app_page({parent: wrapper, title: __("Customer Intake"), single_column: true});
    var content = frappe.render_template("customer-intake", {});
    $(page.body).append(content);

    var currentCustomer = null;
    var searchTimer = null;

    function clearForm() {
        currentCustomer = null;
        $("#cust-name, #cust-number, #cust-phone, #cust-address, #cust-city, #cust-state, #cust-zip, #cust-contacts, #cust-email, #cust-hours").val("");
        $("#search-results").empty();
        $("#no-match").hide();
        $("#cust-status").text("");
    }

    function fillForm(c) {
        currentCustomer = c;
        $("#cust-name").val(c.customer_name || "");
        $("#cust-number").val(c.customer_number || "");
        $("#cust-phone").val(c.phone || c.address_phone || "");
        $("#cust-address").val(c.address_line1 || "");
        $("#cust-city").val(c.city || "");
        $("#cust-state").val(c.state || "");
        $("#cust-zip").val(c.pincode || "");
        $("#cust-contacts").val(c.contact_persons || "");
        $("#cust-email").val(c.email_id || "");
        $("#cust-hours").val(c.hours_of_operation || "");
        $("#cust-status").text("Selected: " + (c.customer_name || c.name));
        $("#no-match").hide();
    }

    function doSearch() {
        var q = $("#intake-search").val().trim();
        if (q.length < 2) { $("#search-results").empty(); return; }
        frappe.call({
            method: "westech_r2.page.customer-intake.customer-intake.search_customers",
            args: {q: q},
            callback: function(r) {
                var list = $("#search-results").empty();
                if (r.message && r.message.length) {
                    r.message.forEach(function(c) {
                        var item = $('<div class="list-group-item" style="cursor:pointer;">')
                            .html('<b>' + frappe.utils.escape_html(c.customer_name || c.name) + '</b> ' +
                                (c.address_line1 ? '<br>' + frappe.utils.escape_html(c.address_line1) : '') +
                                (c.city ? ', ' + c.city : '') +
                                (c.phone ? ' <br><small>' + c.phone + '</small>' : ''));
                        item.on("click", function() { fillForm(c); });
                        list.append(item);
                    });
                    $("#no-match").hide();
                } else {
                    $("#no-match").show();
                }
            }
        });
    }

    $("#intake-search").on("input", function() {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(doSearch, 300);
    });

    $("#btn-add-new").click(function() {
        clearForm();
        $("#cust-name").val($("#intake-search").val());
        $("#cust-status").text("Adding new customer...");
    });

    $("#btn-save-cust").click(function() {
        var data = {
            customer_name: $("#cust-name").val(),
            customer_number: $("#cust-number").val(),
            phone: $("#cust-phone").val(),
            address_line1: $("#cust-address").val(),
            city: $("#cust-city").val(),
            state: $("#cust-state").val(),
            pincode: $("#cust-zip").val(),
            contact_persons: $("#cust-contacts").val(),
            email_id: $("#cust-email").val(),
            hours_of_operation: $("#cust-hours").val()
        };
        if (currentCustomer && currentCustomer.name) {
            data.name = currentCustomer.name;
        }
        frappe.call({
            method: "westech_r2.page.customer-intake.customer-intake.create_customer_from_intake",
            args: {data: JSON.stringify(data)},
            callback: function(r) {
                if (r.message && r.message.status === "ok") {
                    currentCustomer = {name: r.message.customer, customer_name: data.customer_name};
                    $("#cust-status").text("Saved: " + r.message.customer);
                    frappe.show_alert("Customer saved", 3);
                } else {
                    frappe.show_alert("Error saving customer", 5);
                }
            }
        });
    });

    $("#btn-create-pallet").click(function() {
        if (!currentCustomer || !currentCustomer.name) {
            frappe.msgprint("Please select or save a customer first.");
            return;
        }
        frappe.call({
            method: "westech_r2.page.customer-intake.customer-intake.create_pallet",
            args: {
                data: JSON.stringify({
                    customer: currentCustomer.name,
                    customer_number: $("#cust-number").val(),
                    data_status: $("#pallet-data-status").val(),
                    status: $("#pallet-status").val(),
                    inbound_weight: $("#pallet-weight").val()
                })
            },
            callback: function(r) {
                if (r.message && r.message.status === "ok") {
                    frappe.msgprint("Pallet created: " + r.message.pallet);
                    $("#cust-status").text("Pallet: " + r.message.pallet);
                }
            }
        });
    });
};
