// Copyright (c) 2025, Cloud Portal and contributors
// For license information, please see license.txt

frappe.ui.form.on("Cloud Container", {
    refresh(frm) {
        // Add status indicator
        if (frm.doc.status) {
            let indicator = "grey";
            if (frm.doc.status === "Running") indicator = "green";
            else if (frm.doc.status === "Stopped") indicator = "orange";
            else if (frm.doc.status === "Error") indicator = "red";
            else if (frm.doc.status === "Creating") indicator = "blue";

            frm.page.set_indicator(frm.doc.status, indicator);
        }

        // Add action buttons for existing containers
        if (!frm.is_new() && frm.doc.status !== "Pending" && frm.doc.status !== "Creating") {

            // Start button
            if (frm.doc.status === "Stopped" || frm.doc.status === "Error") {
                frm.add_custom_button(__("Start"), function() {
                    frappe.confirm(
                        __("Start container {0}?", [frm.doc.container_name]),
                        function() {
                            frappe.call({
                                method: "cloud_portal.cloud_portal.doctype.cloud_container.cloud_container.start_user_container",
                                args: { name: frm.doc.name },
                                freeze: true,
                                freeze_message: __("Starting container..."),
                                callback: function(r) {
                                    if (r.message && r.message.success) {
                                        frappe.show_alert({
                                            message: __("Container started"),
                                            indicator: "green"
                                        });
                                        frm.reload_doc();
                                    } else {
                                        frappe.msgprint({
                                            title: __("Error"),
                                            message: r.message ? r.message.error : __("Failed to start"),
                                            indicator: "red"
                                        });
                                    }
                                }
                            });
                        }
                    );
                }, __("Actions"));
            }

            // Stop button
            if (frm.doc.status === "Running") {
                frm.add_custom_button(__("Stop"), function() {
                    frappe.confirm(
                        __("Stop container {0}?", [frm.doc.container_name]),
                        function() {
                            frappe.call({
                                method: "cloud_portal.cloud_portal.doctype.cloud_container.cloud_container.stop_user_container",
                                args: { name: frm.doc.name },
                                freeze: true,
                                freeze_message: __("Stopping container..."),
                                callback: function(r) {
                                    if (r.message && r.message.success) {
                                        frappe.show_alert({
                                            message: __("Container stopped"),
                                            indicator: "orange"
                                        });
                                        frm.reload_doc();
                                    } else {
                                        frappe.msgprint({
                                            title: __("Error"),
                                            message: r.message ? r.message.error : __("Failed to stop"),
                                            indicator: "red"
                                        });
                                    }
                                }
                            });
                        }
                    );
                }, __("Actions"));
            }

            // Sync status button
            frm.add_custom_button(__("Sync Status"), function() {
                frappe.call({
                    method: "cloud_portal.cloud_portal.doctype.cloud_container.cloud_container.sync_container_status",
                    args: { name: frm.doc.name },
                    freeze: true,
                    freeze_message: __("Syncing status..."),
                    callback: function(r) {
                        if (r.message && r.message.success) {
                            frappe.show_alert({
                                message: __("Status synced: {0}", [r.message.status]),
                                indicator: "green"
                            });
                            frm.reload_doc();
                        } else {
                            frappe.msgprint({
                                title: __("Error"),
                                message: r.message ? r.message.error : __("Failed to sync"),
                                indicator: "red"
                            });
                        }
                    }
                });
            }, __("Actions"));

            // Delete button
            frm.add_custom_button(__("Delete Container"), function() {
                frappe.confirm(
                    __("Are you sure you want to delete container {0}? This action cannot be undone.", [frm.doc.container_name]),
                    function() {
                        frappe.call({
                            method: "cloud_portal.cloud_portal.doctype.cloud_container.cloud_container.delete_user_container",
                            args: { name: frm.doc.name },
                            freeze: true,
                            freeze_message: __("Deleting container..."),
                            callback: function(r) {
                                if (r.message && r.message.success) {
                                    frappe.show_alert({
                                        message: __("Container deleted"),
                                        indicator: "green"
                                    });
                                    frappe.set_route("List", "Cloud Container");
                                } else {
                                    frappe.msgprint({
                                        title: __("Error"),
                                        message: r.message ? r.message.error : __("Failed to delete"),
                                        indicator: "red"
                                    });
                                }
                            }
                        });
                    }
                );
            }, __("Actions"));
        }

        // Auto-refresh while creating
        if (frm.doc.status === "Creating") {
            frm.dashboard.add_comment(__("Container is being created. This page will refresh automatically."), "blue", true);

            setTimeout(function() {
                frm.reload_doc();
            }, 5000);
        }
    },

    container_name(frm) {
        // Validate container name format
        let name = frm.doc.container_name;
        if (name) {
            // Only allow lowercase letters, numbers, and hyphens
            let clean_name = name.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/--+/g, "-");
            if (clean_name !== name) {
                frm.set_value("container_name", clean_name);
                frappe.show_alert({
                    message: __("Container name cleaned: only lowercase letters, numbers, and hyphens allowed"),
                    indicator: "orange"
                });
            }
        }
    }
});
