frappe.pages["load-update"].on_page_load = function(wrapper) {
    var page = frappe.ui.make_app_page({
        parent: wrapper,
        title: "Load Update",
        single_column: true
    });
    
    var loadName = frappe.utils.get_url_arg("load");
    if (!loadName) {
        $(page.body).html("<div style='padding:40px;text-align:center;'><h2>No load specified</h2><p>Use ?load=MMDDYYYY-XXXX</p></div>");
        return;
    }

    function loadLoad() {
        frappe.call({
            method: "frappe.client.get",
            args: { doctype: "Load", name: loadName },
            callback: function(r) {
                if (r.message) { renderForm(page, r.message); }
                else { $(page.body).html("<div style='padding:40px;text-align:center;'><h2>Load not found</h2></div>"); }
            }
        });
    }

    function renderForm(page, load) {
        var h = "<div style='padding:20px;'>";
        h += "<h2>Update Load: " + load.name + "</h2>";
        h += "<p>Date: " + (load.incoming_date || "N/A") + " | Customer: " + (load.customer_name || load.customer_number || "N/A") + "</p>";
        h += "<div style='margin-bottom:15px;'>";
        h += "<button id='lu-save' class='btn btn-primary'>Save Changes</button> ";
        h += "<button id='lu-print' class='btn btn-default'>Print Worksheet</button> ";
        h += "<a href='/app/load/" + encodeURIComponent(load.name) + "' class='btn btn-default'>Open Form View</a>";
        h += "</div>";
        h += "<table style='width:100%;border-collapse:collapse;font-size:13px;'>";
        h += "<thead><tr style='background:#37474f;color:white;'>";
        h += "<th>Material Type</th><th>Count</th><th>Recv Status</th><th>Send To</th>";
        h += "<th>Recv'd</th><th>HDD Out</th><th>Dis Send To</th>";
        h += "<th>Sanitized</th><th>Test Status</th><th>Test Send</th>";
        h += "<th>R2 Sent</th><th>Phys</th><th>HDD Need</th><th>HDD Phys</th><th>HDD Logic</th>";
        h += "</tr></thead><tbody>";

        if (load.material_items && load.material_items.length > 0) {
            load.material_items.forEach(function(item, idx) {
                var prefix = "item_" + idx + "_";
                h += "<tr style='border-bottom:1px solid #e0e0e0;'>";
                h += "<td><strong>" + (item.material_type || "") + "</strong></td>";
                h += "<td><input type='number' id='" + prefix + "total_count' value='" + (item.total_count || 0) + "' style='width:50px;'></td>";
                h += "<td><input type='text' id='" + prefix + "initial_data_status' value='" + (item.initial_data_status || "") + "' style='width:60px;'></td>";
                h += "<td><input type='text' id='" + prefix + "send_to' value='" + (item.send_to || "") + "' style='width:80px;'></td>";
                h += "<td><input type='number' id='" + prefix + "devices_received' value='" + (item.devices_received || 0) + "' style='width:50px;'></td>";
                h += "<td><input type='number' id='" + prefix + "hdd_removed' value='" + (item.hdd_removed || 0) + "' style='width:50px;'></td>";
                h += "<td><input type='text' id='" + prefix + "disassembly_send_to' value='" + (item.disassembly_send_to || "") + "' style='width:80px;'></td>";
                h += "<td><input type='number' id='" + prefix + "units_sanitized_software' value='" + (item.units_sanitized_software || 0) + "' style='width:50px;'></td>";
                h += "<td><input type='text' id='" + prefix + "test_data_status' value='" + (item.test_data_status || "") + "' style='width:60px;'></td>";
                h += "<td><input type='text' id='" + prefix + "test_send_to' value='" + (item.test_send_to || "") + "' style='width:80px;'></td>";
                h += "<td><input type='number' id='" + prefix + "r2_units_sent' value='" + (item.r2_units_sent || 0) + "' style='width:50px;'></td>";
                h += "<td><input type='number' id='" + prefix + "units_physical_destruction' value='" + (item.units_physical_destruction || 0) + "' style='width:50px;'></td>";
                h += "<td><input type='number' id='" + prefix + "hdd_needs_sanitize' value='" + (item.hdd_needs_sanitize || 0) + "' style='width:50px;'></td>";
                h += "<td><input type='number' id='" + prefix + "hdd_physical_destruction' value='" + (item.hdd_physical_destruction || 0) + "' style='width:50px;'></td>";
                h += "<td><input type='number' id='" + prefix + "hdd_logical_sanitization' value='" + (item.hdd_logical_sanitization || 0) + "' style='width:50px;'></td>";
                h += "</tr>";
            });
        }
        h += "</tbody></table></div>";
        $(page.body).html(h);

        $("#lu-save").on("click", function() {
            var items = [];
            load.material_items.forEach(function(item, idx) {
                var prefix = "#item_" + idx + "_";
                items.push({
                    name: item.name,
                    total_count: parseInt($(prefix + "total_count").val()) || 0,
                    initial_data_status: $(prefix + "initial_data_status").val(),
                    send_to: $(prefix + "send_to").val(),
                    devices_received: parseInt($(prefix + "devices_received").val()) || 0,
                    hdd_removed: parseInt($(prefix + "hdd_removed").val()) || 0,
                    disassembly_send_to: $(prefix + "disassembly_send_to").val(),
                    units_sanitized_software: parseInt($(prefix + "units_sanitized_software").val()) || 0,
                    test_data_status: $(prefix + "test_data_status").val(),
                    test_send_to: $(prefix + "test_send_to").val(),
                    r2_units_sent: parseInt($(prefix + "r2_units_sent").val()) || 0,
                    units_physical_destruction: parseInt($(prefix + "units_physical_destruction").val()) || 0,
                    hdd_needs_sanitize: parseInt($(prefix + "hdd_needs_sanitize").val()) || 0,
                    hdd_physical_destruction: parseInt($(prefix + "hdd_physical_destruction").val()) || 0,
                    hdd_logical_sanitization: parseInt($(prefix + "hdd_logical_sanitization").val()) || 0
                });
            });
            frappe.call({
                method: "westech_r2.page.load-update.load-update.save_load_items",
                args: { load_name: loadName, items: JSON.stringify(items) },
                callback: function(r) {
                    if (r.message && r.message.status === "ok") {
                        frappe.show_alert({message: "Saved", indicator: "green"});
                        loadLoad();
                    } else {
                        frappe.show_alert({message: "Save failed", indicator: "red"});
                    }
                }
            });
        });

        $("#lu-print").on("click", function() {
            window.print();
        });
    }

    loadLoad();
};
