/*******************************************************************************
Copyright (c) 2025, Jan Koester jan.koester@gmx.net
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/

#include <sstream> // For JSON property serialization
#include <iostream> // For logError
#include <cstring> // For strcmp

#include <tinyxml2.h>
#include <htmlpp/html.h>

#include "plugin.h"

extern "C" {
    namespace blogi::webedit {

        class Container : public EditPlugin {
        private:
            std::string content;
            std::string backgroundColor = "";
            std::string width = "";
            std::string height = "";
            std::string m_width = "";
            std::string m_height = "";

        public:
            Container() {
                // NOTE: The base EditPlugin constructor handles ID generation.
                // We set the Type ID here, assuming Type is a member of EditPlugin
                Type="a22a7ef9-0d43-4c1d-82b4-7d34b9545a24";
            };

            virtual ~Container() = default;

            const std::string getName() const override {
                return "Container";
            };

            const std::string getAuthor() const override {
                return "Jan Koester";
            };

            const std::string getVersion() const override {
                return "1.0";
            };

            void logError(const std::string& message) override {
                std::cerr << "ContainerPlugin Error (" << getInstanceId().c_str() << "): " << message << std::endl;
            }

            // --- UI Settings (Stub) ---
            void Settings(libhttppp::HttpRequest &curreq, libhtmlpp::HtmlElement &settings) override {
                // Basic Settings implementation
                libhtmlpp::HtmlElement title("h3");
                title.appendChild(libhtmlpp::TextElement("Container Settings"));
                settings.appendChild(title);
            }

            // --- JSON API (Structural & Bulk Operations) ---
            void JsonApi(json_object *request, json_object *response) override {
                // This method handles structural operations (Add/Delete/Move) and bulk property modifications.

                // --- 1. Request Validation (Placeholder) ---
                // NOTE: Assuming external json_object library functions are available.

                json_object *action_obj = nullptr;
                const char *action = nullptr;

                if (request == nullptr /* || json_object_get_type(request) != json_type_object */) {
                    logError("Invalid JSON request received (nullptr or not object).");
                    return;
                }

                if (json_object_object_get_ex(request, "action", &action_obj)) {
                    action = json_object_get_string(action_obj);
                }


                if (action == nullptr || action[0] == '\0') {
                    logError("No action specified in JsonApi request.");
                    return;
                }

                // --- 3. Action Dispatcher (Structural Changes) ---

                if (strcmp(action, "add") == 0) {
                    // ADD operation: Create a new plugin and attach it.

                    const char *type_id = nullptr;   // Plugin type to create
                    const char *position = nullptr; // "child" or "next"

                    // Placeholder: Extract type_id and position from request

                    json_object *type_id_obj = nullptr;
                    if (json_object_object_get_ex(request, "type_id", &type_id_obj)) {
                        type_id = json_object_get_string(type_id_obj);
                    }

                    json_object *position_obj = nullptr;
                    if (json_object_object_get_ex(request, "position", &position_obj)) {
                        position = json_object_get_string(position_obj);
                    }

                    if (type_id) {
                        // External Dependency: Assumes a factory is available
                        std::unique_ptr<EditPlugin> new_el=std::make_unique<Container>();
                        if (new_el) {
                            if (position != nullptr && strcmp(position, "child") == 0) {
                                this->setChildElement(*new_el);
                            } else { // Assume "next" or sibling append
                                this->addNextElement(*new_el);
                            }
                        } else {
                            logError("Plugin type not found for ADD action.");
                        }
                    } else {
                        logError("Missing 'type_id' for ADD action.");
                    }

                } else if (strcmp(action, "delete") == 0) {

                    const char *target_id = nullptr;

                    if (target_id) {
                        EditPlugin *el_to_remove = nullptr;

                        // Check if it's the first child
                        if (this->child != nullptr && this->child->getInstanceId() == target_id) {
                            el_to_remove = this->child;
                            this->unsetChildElement(*el_to_remove);
                        } else {
                            // Traverse siblings to find the element *before* target_id
                            EditPlugin *cur = this->child;
                            while(cur != nullptr && cur->nextElement() != nullptr) {
                                if (cur->nextElement()->getInstanceId() == target_id) {
                                    el_to_remove = const_cast<EditPlugin*>(cur->nextElement());
                                    this->remNextElement(*el_to_remove);
                                    break;
                                }
                                cur = const_cast<EditPlugin*>(cur->nextElement());
                            }
                        }

                        if (el_to_remove) {
                            // Placeholder: Send Success response
                        } else {
                            logError("Target ID not found for DELETE action.");
                            // Placeholder: Send Error response
                        }
                    }
                } else if (strcmp(action, "modify_bulk") == 0) {
                    // BULK MODIFY operation: Update multiple properties at once.
                    json_object *properties_obj = nullptr;
                    if (json_object_object_get_ex(request, "properties", &properties_obj)) {
                        const char *json_str = json_object_to_json_string_ext(properties_obj, JSON_C_TO_STRING_NOSLASHESCAPE);
                        if (json_str) {
                            fromPropertiesJson(json_str);
                        }
                    }

                } else if (strcmp(action, "read") == 0) {
                    // READ operation: Fetch properties or structural info.
                    json_object *result_obj = json_object_new_object();
                    json_object_object_add(result_obj, "properties", json_object_new_string(toPropertiesJson().c_str()));
                    if (response) {
                        json_object_object_add(response, "data", result_obj);
                    }
                } else if (strcmp(action, "get_schema") == 0) {
                    if (response) {
                        json_object_object_add(response, "schema", getSchemaJson());
                    }
                }

                // --- 4. Final Response Construction ---
                if (response != nullptr) {
                    json_object_object_add(response, "status", json_object_new_string("success"));
                    json_object_object_add(response, "plugin_type", json_object_new_string("Container"));
                }
            }

            // --- Schema ---
            static json_object* getSchemaJson() {
                json_object *arr = json_object_new_array();
                auto addField = [&](const char *key, const char *label, const char *type,
                                    const char *placeholder = nullptr, const char *target = "all",
                                    json_object *options = nullptr) {
                    json_object *f = json_object_new_object();
                    json_object_object_add(f, "key", json_object_new_string(key));
                    json_object_object_add(f, "label", json_object_new_string(label));
                    json_object_object_add(f, "type", json_object_new_string(type));
                    if (placeholder) json_object_object_add(f, "placeholder", json_object_new_string(placeholder));
                    json_object_object_add(f, "target", json_object_new_string(target));
                    if (options) json_object_object_add(f, "options", options);
                    json_object_array_add(arr, f);
                };
                auto mkOpts = [](std::initializer_list<const char*> vals) {
                    json_object *a = json_object_new_array();
                    for (auto v : vals) json_object_array_add(a, json_object_new_string(v));
                    return a;
                };
                addField("background_color", "Background Color (Dark)", "color_var", nullptr, "desktop");
                addField("l_background_color", "Background Color (Light)", "color_var", nullptr, "light");
                addField("width", "Width", "text", "e.g. 100%", "desktop");
                addField("height", "Height", "text", "e.g. auto", "desktop");
                addField("css_class", "CSS Class", "text", "e.g. my-container");
                addField("border_radius", "Border Radius", "text", "e.g. 8px", "desktop");
                addField("border_style", "Border", "text", "e.g. 1px solid #ccc", "desktop");
                addField("opacity", "Opacity", "text", "0.0 - 1.0", "desktop");
                addField("vertical_align", "Vertical Align", "select", nullptr, "desktop", mkOpts({"top","center","bottom"}));
                addField("hidden", "Hidden", "checkbox", nullptr, "desktop");
                {
                    json_object *hf = json_object_array_get_idx(arr, json_object_array_length(arr) - 1);
                    json_object_object_add(hf, "default", json_object_new_boolean(false));
                }
                return arr;
            }

            // --- XML Persistence (Save/Load State) ---

            /**
             * @brief Serializes the element and its children to an XML object.
             */
            tinyxml2::XMLElement* toXmlObject(tinyxml2::XMLDocument* doc) override {
                tinyxml2::XMLElement* element = doc->NewElement(getName().c_str());
                element->SetAttribute("instance_id", getInstanceId().c_str());
                element->SetAttribute("type_id", getTypeId().c_str());

                // Persist background color
                element->SetAttribute("background_color", backgroundColor.c_str());
                element->SetAttribute("width", width.c_str());
                element->SetAttribute("height", height.c_str());
                element->SetAttribute("m_width", m_width.c_str());
                element->SetAttribute("m_height", m_height.c_str());

                // Add content
                if (!content.empty()) {
                    element->SetText(content.c_str());
                }

                const EditPlugin *cur = child;
                while (cur) {
                    // toXmlObject is non-const but the recursive call is fine
                    element->InsertEndChild(const_cast<EditPlugin*>(cur)->toXmlObject(doc));
                    cur = cur->nextElement(); // Use base class accessor for siblings
                }

                return element;
            }

            void fromXmlObject(tinyxml2::XMLElement* xml_data) override {
                const char* loaded_content = xml_data->GetText();
                if (loaded_content) {
                    content = loaded_content;
                }
                // Load background color attribute
                const char* loaded_color = xml_data->Attribute("background_color");
                if (loaded_color) {
                    backgroundColor = loaded_color;
                }
                const char* val = nullptr;
                val = xml_data->Attribute("width");
                if (val) width = val;
                val = xml_data->Attribute("height");
                if (val) height = val;
                val = xml_data->Attribute("m_width");
                if (val) m_width = val;
                val = xml_data->Attribute("m_height");
                if (val) m_height = val;
                // NOTE: Loading children from XML requires an EditPluginFactory which is not available here.
            }

            // --- JSON API (Modify/Read Properties) ---

            // Serialize properties to JSON for the API/UI (Read operation)
            std::string toPropertiesJson() {
                json_object *obj = json_object_new_object();
                json_object_object_add(obj, "background_color", json_object_new_string(backgroundColor.c_str()));
                json_object_object_add(obj, "width", json_object_new_string(width.c_str()));
                json_object_object_add(obj, "height", json_object_new_string(height.c_str()));
                json_object_object_add(obj, "m_width", json_object_new_string(m_width.c_str()));
                json_object_object_add(obj, "m_height", json_object_new_string(m_height.c_str()));
                std::string result = json_object_to_json_string_ext(obj, JSON_C_TO_STRING_NOSLASHESCAPE);
                json_object_put(obj);
                return result;
            }

            // Deserialize properties from JSON received from the API/UI (Modify/Delete operation)
            void fromPropertiesJson(const std::string &json) {
                json_object *obj = json_tokener_parse(json.c_str());
                if (!obj) return;

                json_object *val_obj = nullptr;
                const char *val = nullptr;

                if (json_object_object_get_ex(obj, "background_color", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) backgroundColor = val;
                }
                if (json_object_object_get_ex(obj, "width", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) width = val;
                }
                if (json_object_object_get_ex(obj, "height", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) height = val;
                }
                if (json_object_object_get_ex(obj, "m_width", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_width = val;
                }
                if (json_object_object_get_ex(obj, "m_height", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_height = val;
                }

                json_object_put(obj);
            }

            // --- HTML Rendering ---

            /**
             * @brief Renders the container element and recursively renders its children.
             */
            void Render(libhtmlpp::HtmlElement &el) const override {
                libhtmlpp::HtmlElement cnt("div");

                std::string responsiveClass = std::string("we-") + getInstanceId().c_str();

                std::string style = "padding: 10px; min-height: 50px;";

                if (!backgroundColor.empty() && backgroundColor != "none" && backgroundColor != "transparent") {
                    style += " background-color: " + backgroundColor + ";";
                } else {
                    style += " border: 1px dashed var(--blogi-border, #ccc);";
                }
                if (!width.empty()) {
                    style += " width: " + width + ";";
                }
                if (!height.empty()) {
                    style += " height: " + height + ";";
                }

                cnt.setAttribute("style", style.c_str());
                cnt.setAttribute("class", responsiveClass.c_str());

                // Mobile responsive overrides
                std::string mobileCSS;
                if (!m_width.empty()) mobileCSS += " width: " + m_width + " !important;";
                if (!m_height.empty()) mobileCSS += " height: " + m_height + " !important;";

                if (!mobileCSS.empty()) {
                    libhtmlpp::HtmlElement styleTag("style");
                    std::string mediaRule = "@media (max-width: 768px) { ." + responsiveClass + " {" + mobileCSS + " } }";
                    styleTag.appendChild(libhtmlpp::TextElement(mediaRule.c_str()));
                    el.appendChild(styleTag);
                }

                // Placeholder: Add content if any
                if (!content.empty()) {
                    cnt.appendChild(libhtmlpp::TextElement(content.c_str()));
                }

                // Recursively render children
                const EditPlugin *cur = child;
                while (cur) {
                    cur->Render(cnt);
                    cur = cur->nextElement(); // Changed to use the base class's accessor
                }

                el.appendChild(cnt);
            }

            // --- Element Management API (Add/Delete Structural Elements) ---

            bool canHaveChildren() const override { return true; }

            bool haveChilds() override { return child != nullptr; }

            /**
             * @brief Sets the first child element of this container.
             * @param el The EditPlugin element to be set as the first child.
             */
            void setChildElement(const EditPlugin &el) override {
                child = const_cast<EditPlugin*>(&el);
            }

            void unsetChildElement(const EditPlugin &el) override {
                if (child == &el) {
                    child = const_cast<EditPlugin*>(el.nextElement());
                }
            }

            /**
             * @brief Adds a new element as a sibling to the last element in the list.
             * @param el The EditPlugin element to be added.
             */
            void addNextElement(const EditPlugin &el) override {
                EditPlugin *newEl = const_cast<EditPlugin*>(&el);

                if (!child) {
                    setChildElement(el);
                    return;
                }

                EditPlugin *cur = child;
                while (cur->nextElement() != nullptr) {
                    cur = const_cast<EditPlugin*>(cur->nextElement());
                }
                cur->setNextEl(newEl);
            }
            void remNextElement(const EditPlugin &el) override {
                if (!child) return;

                if (child == &el) {
                    unsetChildElement(el);
                    return;
                }

                EditPlugin *cur = child;
                while (cur->nextElement() != nullptr) {
                    if (cur->nextElement() == &el) {
                        cur->setNextEl(const_cast<EditPlugin*>(el.nextElement()));
                        return;
                    }
                    cur = const_cast<EditPlugin*>(cur->nextElement());
                }
            }
        };
    };
}

// --- Factory Functions ---

EXPORT blogi::webedit::Container* create() {
    return new blogi::webedit::Container();
}

EXPORT void destroy(blogi::webedit::Container* p) {
    delete p;
}
