<?php

namespace GriffinForms\Admin\App\Html\Modals\Integrations;

/**
 * Integrations Modal - Scripts Trait
 *
 * Outputs JavaScript for the integrations modal.
 * Handles modal interactions, event listeners, and AJAX calls.
 */
trait Scripts
{
    /**
     * Setup and initialize modal JavaScript
     */
    protected function setupJs()
    {
        $this->outputPreludeJs();
        $this->outputModalShowEventJs();
        $this->outputLoadGridViewJs();
        $this->outputCardClickHandlerJs();
    }

    /**
     * Output JavaScript prelude - Setup state and helper functions
     */
    private function outputPreludeJs()
    {
        $nonce = wp_create_nonce('griffinforms-integrations');
        echo '
        // Integrations Modal State and Helpers
        const integrationsModalId = "#griffinforms-builder-modal-integrations";
        const integrationsMessageContainer = $(".griffinforms-integrations-message-container");
        const integrationsContentContainer = $(".griffinforms-integrations-content");

        // Store nonce globally for all AJAX calls
        window.griffinformsIntegrationsNonce = "' . esc_js($nonce) . '";

        /**
         * Display message in integrations modal
         * @param {string} type - Message type: "success" or "danger"
         * @param {string} message - Message text
         */
        function showIntegrationsMessage(type, message) {
            const noticeClass = type === "success" ? "gf-notice-success" : "gf-notice-danger";
            const notice = jQuery("<div>", {
                class: "gf-notice " + noticeClass,
                role: "alert"
            });
            notice.text(message);
            integrationsMessageContainer.empty().append(notice);

            // Scroll message into view smoothly
            setTimeout(() => {
                const element = integrationsMessageContainer.get(0);
                if (element && element.scrollIntoView) {
                    element.scrollIntoView({ behavior: "smooth", block: "nearest" });
                }
            }, 50);
        }

        /**
         * Hide message in integrations modal
         */
        function hideIntegrationsMessage() {
            integrationsMessageContainer.empty();
        }

        /**
         * Show an error inside the integration info area
         */
        function showIntegrationError(message) {
            showIntegrationsMessage("danger", message);
        }

        // Export helper functions to global scope
        window.showIntegrationsMessage = showIntegrationsMessage;
        window.hideIntegrationsMessage = hideIntegrationsMessage;
        ';
    }

    /**
     * Output JavaScript for modal show event
     */
    private function outputModalShowEventJs()
    {
        echo '
        // Handle modal show event
        const integrationsModal = $(integrationsModalId);

        if (integrationsModal.length) {
            integrationsModal.on("show.bs.modal", function() {
                // Load integrations grid when modal opens
                loadIntegrationsGrid();
            });

            // Clear state when modal is hidden
            integrationsModal.on("hide.bs.modal", function() {
                hideIntegrationsMessage();
            });
        }

        // Command palette context: open directly to a specific provider info view.
        document.addEventListener("gf-palette-modal-context", function(e) {
            if (!e.detail || e.detail.modal_id !== "griffinforms-builder-modal-integrations") { return; }
            var providerId = e.detail.context && e.detail.context.provider_id;
            if (!providerId) { return; }
            integrationsModal.one("shown.bs.modal", function() {
                if (typeof window.loadIntegrationInfo === "function") {
                    window.loadIntegrationInfo(providerId);
                }
            });
        });
        ';
    }

    /**
     * Output JavaScript to load integrations grid view
     */
    private function outputLoadGridViewJs()
    {
        echo '
        /**
         * Show skeleton loading placeholders
         */
        function showSkeletonLoading() {
            let skeletonHtml = \'<div class="gf-integrations-filters"></div>\';
            skeletonHtml += \'<div class="gf-integrations-grid loading">\';

            // Create 12 skeleton cards
            for (let i = 0; i < 12; i++) {
                skeletonHtml += \'<div class="gf-integration-card skeleton"></div>\';
            }

            skeletonHtml += \'</div>\';
            integrationsContentContainer.html(skeletonHtml);
        }

        /**
         * Phase 1: Load integrations grid view
         */
        function loadIntegrationsGrid() {
            // Show modal spinner
            const modal = $(integrationsModalId);
            const spinner = modal.find(".griffinforms-modal-spinner");
            if (spinner.length) {
                spinner.removeClass("d-none");
            }

            // Show skeleton placeholders
            showSkeletonLoading();

            $.ajax({
                url: ajaxurl,
                type: "POST",
                data: {
                    action: "getIntegrationsList",
                    nonce: window.griffinformsIntegrationsNonce
                },
                success: function(response) {
                    if (response.success) {
                        // Render grid HTML
                        integrationsContentContainer.html(response.data.html);
                        hideIntegrationsMessage();

                        // Store categories data for filtering
                        window.integrationsData = response.data.providers || {};
                        window.integrationsCategories = response.data.categories || [];

                        // Attach click handlers to integration cards
                        attachCardClickHandlers();
                        attachCategoryFilterHandlers();
                    } else {
                        const errorMsg = (response.data && response.data.msg) ? response.data.msg : "Failed to load integrations";
                        showIntegrationsMessage("danger", errorMsg);
                        console.error("Integrations Error Response:", response);
                    }
                },
                error: function(xhr, status, error) {
                    console.error("Integrations AJAX Error:", {status: status, error: error, xhr: xhr});
                    let errorMsg = "Error loading integrations: " + error;
                    if (xhr.responseText) {
                        errorMsg += " - " + xhr.responseText.substring(0, 200);
                    }
                    showIntegrationsMessage("danger", errorMsg);
                },
                complete: function() {
                    // Hide modal spinner
                    const modal = $(integrationsModalId);
                    const spinner = modal.find(".griffinforms-modal-spinner");
                    if (spinner.length) {
                        spinner.addClass("d-none");
                    }
                }
            });
        }

        // Export to global scope
        window.loadIntegrationsGrid = loadIntegrationsGrid;
        window.showSkeletonLoading = showSkeletonLoading;
        ';
    }

    /**
     * Output JavaScript for integration card click handling and category filtering
     */
    private function outputCardClickHandlerJs()
    {
        echo '
        /**
         * Load integration info view
         */
        function loadIntegrationInfo(integrationId) {
            const modal = $(integrationsModalId);
            const spinner = modal.find(".griffinforms-modal-spinner");
            if (spinner.length) {
                spinner.removeClass("d-none");
            }

            $.ajax({
                url: ajaxurl,
                type: "POST",
                data: {
                    action: "getIntegrationInfo",
                    nonce: window.griffinformsIntegrationsNonce,
                    integration_id: integrationId
                },
                success: function(response) {
                    if (response.success) {
                        // Replace grid view with info view
                        integrationsContentContainer.html(response.data.html);
                        hideIntegrationsMessage();

                        // Attach event handlers for the info view
                        attachInfoViewHandlers(integrationId);
                    } else {
                        const errorMsg = (response.data && response.data.msg) ? response.data.msg : "Failed to load integration info";
                        showIntegrationsMessage("danger", errorMsg);
                        console.error("Integration Info Error Response:", response);
                    }
                },
                error: function(xhr, status, error) {
                    console.error("Integration Info AJAX Error:", {status: status, error: error, xhr: xhr});
                    let errorMsg = "Error loading integration info: " + error;
                    if (xhr.responseText) {
                        errorMsg += " - " + xhr.responseText.substring(0, 200);
                    }
                    showIntegrationsMessage("danger", errorMsg);
                },
                complete: function() {
                    // Hide modal spinner
                    const modal = $(integrationsModalId);
                    const spinner = modal.find(".griffinforms-modal-spinner");
                    if (spinner.length) {
                        spinner.addClass("d-none");
                    }
                }
            });
        }

        /**
         * Load integration configuration form
         */
        function loadIntegrationConfigurationForm(integrationId) {
            const modal = $(integrationsModalId);
            const spinner = modal.find(".griffinforms-modal-spinner");
            if (spinner.length) {
                spinner.removeClass("d-none");
            }

            const formId = griffinformsResolveActiveFormId();

            $.ajax({
                url: ajaxurl,
                type: "POST",
                data: {
                    action: "getIntegrationConfigurationForm",
                    nonce: window.griffinformsIntegrationsNonce,
                    integration_id: integrationId,
                    form_id: formId || ""
                },
                success: function(response) {
                    if (response.success) {
                        // Replace info view with configuration form
                        integrationsContentContainer.html(response.data.html);
                        hideIntegrationsMessage();

                        // Execute configuration JavaScript if provided
                        if (response.data.js) {
                            try {
                                eval(response.data.js);
                            } catch (e) {
                                console.error("Error executing configuration JS:", e);
                            }
                        }
                    } else {
                        const errorMsg = (response.data && response.data.msg) ? response.data.msg : "Failed to load configuration form";
                        showIntegrationsMessage("danger", errorMsg);
                        console.error("Configuration Form Error Response:", response);
                    }
                },
                error: function(xhr, status, error) {
                    console.error("Configuration Form AJAX Error:", {status: status, error: error, xhr: xhr});
                    let errorMsg = "Error loading configuration form: " + error;
                    if (xhr.responseText) {
                        errorMsg += " - " + xhr.responseText.substring(0, 200);
                    }
                    showIntegrationsMessage("danger", errorMsg);
                },
                complete: function() {
                    // Hide modal spinner
                    const modal = $(integrationsModalId);
                    const spinner = modal.find(".griffinforms-modal-spinner");
                    if (spinner.length) {
                        spinner.addClass("d-none");
                    }
                }
            });
        }

        /**
         * Attach event handlers for info view (back button, action buttons)
         */
        function attachInfoViewHandlers(integrationId) {
            // Remove any previously attached handlers to prevent duplicates
            // (prevents handler accumulation when navigating back and forth)
            $(document).off("click", ".gf-integration-info-back");
            $(document).off("click", ".gf-integration-btn-configure");
            $(document).off("click", ".gf-integration-btn-test");
            $(document).off("click", ".gf-integration-btn-disable");
            $(document).off("click", ".gf-integration-btn-form-settings");
            $(document).off("click", ".gf-integration-btn-cancel");
            $(document).off("click", "[data-action=\"save-form-settings\"]");
            $(document).off("click", "[data-action=\"close-form-settings\"]");

            // Back button handler
            $(document).on("click", ".gf-integration-info-back", function(e) {
                e.preventDefault();
                loadIntegrationsGrid();
            });

            // Configure button handler
            $(document).on("click", ".gf-integration-btn-configure", function(e) {
                e.preventDefault();
                const id = $(this).data("integration-id") || integrationId;
                loadIntegrationConfigurationForm(id);
            });

            // Test connection button handler
            $(document).on("click", ".gf-integration-btn-test", function(e) {
                e.preventDefault();
                const id = $(this).data("integration-id") || integrationId;
                testIntegration(id);
            });

            // Disable button handler
            $(document).on("click", ".gf-integration-btn-disable", function(e) {
                e.preventDefault();
                const id = $(this).data("integration-id") || integrationId;
                disableIntegration(id);
            });

            // Config cancel handler (back to info view)
            $(document).on("click", ".gf-integration-btn-cancel", function(e) {
                e.preventDefault();
                const id = $(this).data("integration-id") || integrationId;
                loadIntegrationInfo(id);
            });

            // Form-specific settings handler
            $(document).on("click", ".gf-integration-btn-form-settings", function(e) {
                e.preventDefault();
                const id = $(this).data("integration-id") || integrationId;
                const formId = griffinformsResolveActiveFormId();

                if (!formId) {
                    showIntegrationError("Form ID not found. Open a form to manage form-specific settings.");
                    return;
                }

                const errorMsg = (msg) => {
                    showIntegrationError(msg);
                };

                jQuery.ajax({
                    url: ajaxurl,
                    method: "POST",
                    dataType: "json",
                    data: {
                        action: "getFormIntegrationSettings",
                        nonce: window.griffinformsIntegrationsNonce || "",
                        integration_id: id,
                        form_id: formId,
                    },
                    success: function(response) {
                        if (response.success) {
                            if (response.data && response.data.html) {
                                integrationsContentContainer.html(response.data.html);
                            }
                        } else {
                            errorMsg((response.data && response.data.msg) ? response.data.msg : "Failed to load form settings.");
                        }
                    },
                    error: function() {
                        errorMsg("Failed to load form settings.");
                    }
                });
            });

            // Save form settings
            $(document).on("click", "[data-action=\"save-form-settings\"]", function(e) {
                e.preventDefault();
                const panel = e.currentTarget.closest(".gf-form-settings-panel");
                if (!panel) return;

                const id = $(this).data("integration-id") || integrationId;
                const formId = griffinformsResolveActiveFormId();
                if (!formId) {
                    showIntegrationError("Form ID not found. Open a form to manage form-specific settings.");
                    return;
                }

                const form = panel.querySelector("form.gf-form-settings-form");
                if (!form) return;

                const formData = new FormData(form);
                const settings = {};
                let disableFlag = false;
                let explicitMode = null;

                for (const [key, rawValue] of formData.entries()) {
                    if (key === "__gf_form_settings_mode") {
                        explicitMode = (rawValue || "").toString().trim();
                        continue;
                    }

                    let value = rawValue;
                    if (value === "on" || value === "1") {
                        value = true;
                    } else if (value === "0" || value === "off") {
                        value = false;
                    }

                    settings[key] = value;

                    if (key.indexOf("disable_") === 0 && value === true) {
                        disableFlag = true;
                    }
                }

                let mode = "custom";
                if (explicitMode === "disabled" && disableFlag) {
                    mode = "disabled";
                } else if (disableFlag) {
                    mode = "disabled";
                } else if (explicitMode === "custom") {
                    mode = "custom";
                }

                $.ajax({
                    url: ajaxurl,
                    method: "POST",
                    dataType: "json",
                    data: {
                        action: "saveFormIntegrationSettings",
                        nonce: window.griffinformsIntegrationsNonce || "",
                        integration_id: id,
                        form_id: formId,
                        mode: mode,
                        settings: settings
                    },
                    success: function(response) {
                        if (response.success) {
                            showIntegrationsMessage("success", response.data.message || "Form settings saved.");
                            loadIntegrationInfo(id);
                            try {
                                document.dispatchEvent(new CustomEvent("form-updated", { detail: { type: "integration_settings", formId: formId, integrationId: id } }));
                            } catch (e) {}
                            try {
                                document.dispatchEvent(new CustomEvent("integration-settings-saved", { detail: { formId: formId, integrationId: id, mode: mode } }));
                            } catch (e) {}
                        } else {
                            showIntegrationError((response.data && response.data.msg) ? response.data.msg : "Failed to save form settings.");
                        }
                    },
                    error: function() {
                        showIntegrationError("Failed to save form settings.");
                    }
                });
            });

            // Close form settings panel
            $(document).on("click", "[data-action=\"close-form-settings\"]", function(e) {
                e.preventDefault();
                const id = $(this).data("integration-id") || integrationId;
                loadIntegrationInfo(id);
            });
        }

        /**
         * Resolve current form id from existing helpers/session
         */
        function griffinformsResolveActiveFormId() {
            if (typeof window.griffinformsResolveActiveFormId === "function" && window.griffinformsResolveActiveFormId !== griffinformsResolveActiveFormId) {
                return window.griffinformsResolveActiveFormId();
            }

            const stored = parseInt(window.sessionStorage.getItem("gfFormId"), 10);
            if (!Number.isNaN(stored) && stored > 0) {
                return stored;
            }

            return null;
        }

        /**
         * Attach click handlers to integration cards
         */
        function attachCardClickHandlers() {
            $(document).on("click", ".gf-integration-card", function(e) {
                const integrationId = $(this).data("integration-id");

                if (integrationId) {
                    // Load integration info view
                    loadIntegrationInfo(integrationId);
                }
            });
        }

        /**
         * Attach click handlers to category filter pills and handle filtering
         */
        function attachCategoryFilterHandlers() {
            $(document).on("click", ".gf-integrations-filter-pill", function(e) {
                e.preventDefault();
                const selectedCategory = $(this).data("category");

                // Update active pill
                $(".gf-integrations-filter-pill").removeClass("active");
                $(this).addClass("active");

                // Filter integrations
                filterIntegrationsByCategory(selectedCategory);
            });
        }

        /**
         * Filter integrations by category
         */
        function filterIntegrationsByCategory(category) {
            const cards = $(".gf-integration-card");

            if (category === "all") {
                // Show all cards
                cards.show();
            } else {
                // Hide all cards first
                cards.hide();

                // Show only cards matching the selected category
                cards.each(function() {
                    const integrationId = $(this).data("integration-id");
                    if (window.integrationsData && window.integrationsData[integrationId]) {
                        const provider = window.integrationsData[integrationId];
                        if (provider.category === category) {
                            $(this).show();
                        }
                    }
                });
            }
        }

        /**
         * Test integration connection
         */
        function testIntegration(integrationId) {
            const modal = $(integrationsModalId);
            const spinner = modal.find(".griffinforms-modal-spinner");
            if (spinner.length) {
                spinner.removeClass("d-none");
            }

            const formId = griffinformsResolveActiveFormId();

            $.ajax({
                url: ajaxurl,
                type: "POST",
                dataType: "json",
                data: {
                    action: "testIntegration",
                    nonce: window.griffinformsIntegrationsNonce,
                    integration_id: integrationId,
                    form_id: formId || ""
                },
                success: function(response) {
                    if (response.success) {
                        const msg = response.data.message || "Connection test passed";
                        showIntegrationsMessage("success", msg);
                    } else {
                        const errorMsg = (response.data && response.data.msg) ? response.data.msg : "Connection test failed";
                        showIntegrationsMessage("danger", errorMsg);
                    }
                },
                error: function(xhr, status, error) {
                    let errorMsg = "Error testing connection: " + error;
                    if (xhr.responseText) {
                        errorMsg += " - " + xhr.responseText.substring(0, 200);
                    }
                    showIntegrationsMessage("danger", errorMsg);
                },
                complete: function() {
                    // Hide modal spinner
                    const modal = $(integrationsModalId);
                    const spinner = modal.find(".griffinforms-modal-spinner");
                    if (spinner.length) {
                        spinner.addClass("d-none");
                    }
                }
            });
        }

        /**
         * Disable integration
         */
        function disableIntegration(integrationId) {
            const modal = $(integrationsModalId);
            const spinner = modal.find(".griffinforms-modal-spinner");
            if (spinner.length) {
                spinner.removeClass("d-none");
            }

            const formId = griffinformsResolveActiveFormId();

            $.ajax({
                url: ajaxurl,
                type: "POST",
                dataType: "json",
                data: {
                    action: "disableIntegration",
                    nonce: window.griffinformsIntegrationsNonce,
                    integration_id: integrationId,
                    form_id: formId || ""
                },
                success: function(response) {
                    if (response.success) {
                        showIntegrationsMessage("success", response.data.message || "Integration disabled");
                        // Reload info view after brief delay to show updated status
                        setTimeout(() => {
                            loadIntegrationInfo(integrationId);
                        }, 1000);
                    } else {
                        const errorMsg = (response.data && response.data.msg) ? response.data.msg : "Failed to disable integration";
                        showIntegrationsMessage("danger", errorMsg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error("Disable integration error:", {status: status, error: error, xhr: xhr, response: xhr.responseText});
                    let errorMsg = "Error disabling integration: " + error;
                    if (xhr.responseText) {
                        errorMsg += " - " + xhr.responseText.substring(0, 200);
                    }
                    showIntegrationsMessage("danger", errorMsg);
                },
                complete: function() {
                    // Hide modal spinner
                    const modal = $(integrationsModalId);
                    const spinner = modal.find(".griffinforms-modal-spinner");
                    if (spinner.length) {
                        spinner.addClass("d-none");
                    }
                }
            });
        }

        // Export to global scope
        window.loadIntegrationInfo = loadIntegrationInfo;
        window.loadIntegrationConfigurationForm = loadIntegrationConfigurationForm;
        window.attachCardClickHandlers = attachCardClickHandlers;
        window.attachCategoryFilterHandlers = attachCategoryFilterHandlers;
        window.filterIntegrationsByCategory = filterIntegrationsByCategory;
        window.attachInfoViewHandlers = attachInfoViewHandlers;
        window.testIntegration = testIntegration;
        window.disableIntegration = disableIntegration;
        ';
    }

}
