<?php

namespace GriffinForms\Admin\App\Html\Containers;

final class RightSideBar extends \GriffinForms\Admin\App\Html\Containers\Format
{

    /**
     * Defines widgets for rightsidebar container.
     * @see html\widgets\righsidebar\
     */
    protected function setWidgets()
    {
        if ($this->isAiDraftMode()) {
            $form_id = isset($_GET['form_id']) ? absint(wp_unslash($_GET['form_id'])) : 0;
            $this->ensureAiDraftState($form_id);
            $this->widgets = array('butler_chat');
        } else {
            $this->widgets = array(
                'single_form_summary',
                'multi_form_summary',
                'form_summary',
                'frontend_urls',
                'recent_submissions',
                'form_logs_timeline',
                'item_summary',
                //'field_selection',
                'recent_entries',
            );
        }
    }

    public function getHtml()
    {
        echo '<div id="' . esc_attr($this->getHtmlId()) . '" class="griffinforms-app-sidebar flex-column ms-1 bg-white overflow-hidden">';
        
        if ($this->isAiDraftMode()) {
            $this->widgets['butler_chat']->getHtml();
        } else {
            echo '<div id="griffinforms-app-rightsidebar-accordion" class="accordion accordion-flush" data-gf-context="form-list">';
            $this->widgets['single_form_summary']->getHtml();
            $this->widgets['multi_form_summary']->getHtml();
            echo '</div>';

            echo '<div id="griffinforms-app-rightsidebar-tabs" class="gf-rightsidebar-tabs nav nav-underline" data-gf-context="form-layout" role="tablist">';
            echo '<div class="gf-rightsidebar-tablist">';
            echo '<button type="button" class="nav-link gf-rightsidebar-tab active" data-gf-tab="form" aria-selected="true">' . esc_html__('Form', 'griffinforms-form-builder') . '</button>';
            echo '<button type="button" class="nav-link gf-rightsidebar-tab" data-gf-tab="element" aria-selected="false" style="display:none;">';
            echo '<span class="gf-rightsidebar-tab-label">' . esc_html__('Element', 'griffinforms-form-builder') . '</span>';
            echo '</button>';
            echo '</div>';
            echo '<div class="gf-rightsidebar-tab-actions">';
            echo '<button type="button" class="gf-rightsidebar-accordion-action" data-gf-accordion-action="expand" aria-label="' . esc_attr__('Expand all', 'griffinforms-form-builder') . '">';
            echo '<span class="material-symbols-rounded griffinforms-material-symbol align-text-bottom">add</span>';
            echo '</button>';
            echo '<button type="button" class="gf-rightsidebar-accordion-action" data-gf-accordion-action="collapse" aria-label="' . esc_attr__('Collapse all', 'griffinforms-form-builder') . '">';
            echo '<span class="material-symbols-rounded griffinforms-material-symbol align-text-bottom">remove</span>';
            echo '</button>';
            echo '</div>';
            echo '</div>';

            echo '<div id="griffinforms-app-rightsidebar-accordion" class="accordion accordion-flush" data-gf-context="form-layout">';
            echo '<div class="gf-rightsidebar-tabpanel" data-gf-tabpanel="form">';
            $this->widgets['form_summary']->getHtml();
            $this->widgets['frontend_urls']->getHtml();
            $this->widgets['recent_submissions']->getHtml();
            $this->widgets['form_logs_timeline']->getHtml();
            echo '</div>';
            echo '<div class="gf-rightsidebar-tabpanel" data-gf-tabpanel="element">';
            $this->widgets['item_summary']->getHtml();
            $this->widgets['recent_entries']->getHtml();
            echo '</div>';
            echo '</div>';

            echo '<div id="griffinforms-app-rightsidebar-field-selection" class="pt-2" data-gf-context="form-layout">';
            //$this->widgets['field_selection']->getHtml();
            echo '</div>';
        }
        
        $this->renderSharedModals();

        echo '</div>';
    }

    public function RightSidebarJs()
    {
        ?>
            jQuery(document).ready(function($) {
            <?php
            $this->resizableJs();
            ?>
            });
        <?php
    }

    public function getJs()
    {
        if ($this->isAiDraftMode()) {
            if (isset($this->widgets['butler_chat'])) {
                $this->widgets['butler_chat']->getJs();
            }
        } else {
            //$this->RightSidebarJs();
            $this->tabsJs();
            $this->widgets['single_form_summary']->getJs();
            $this->widgets['multi_form_summary']->getJs();
            $this->widgets['form_summary']->getJs();
            $this->widgets['frontend_urls']->getJs();
            $this->widgets['recent_submissions']->getJs();
            $this->widgets['form_logs_timeline']->getJs();
            $this->widgets['item_summary']->getJs();
            //$this->widgets['field_selection']->getJs();
            $this->widgets['recent_entries']->getJs();
        }
    }

    private function resizableJs()
    {
/*         echo '
        $("#' . esc_attr($this->getHtmlId()) . '").resizable({
            handles: "w",
            distance: 30,
            minWidth: 350,
            maxWidth: 500
        });' . PHP_EOL; */
    }

    private function renderSharedModals()
    {
    }

    private function isAiDraftMode(): bool
    {
        $mode    = isset($_GET['mode'])    ? sanitize_key(wp_unslash($_GET['mode']))    : '';
        $form_id = isset($_GET['form_id']) ? absint(wp_unslash($_GET['form_id']))       : 0;

        return $mode === 'ai_draft' && $form_id > 0;
    }

    private function isAiDraftForm(int $form_id): bool
    {
        if ($form_id <= 0 || $this->sql->itemExists('form', $form_id) === false) {
            return false;
        }

        if ($this->formTableHasColumn('status')) {
            $status = (string) $this->sql->getItemValue($form_id, 'status', 'form');
            if ($status === 'draft') {
                return true;
            }
        }

        $origin = (string) $this->sql->getItemValue($form_id, 'origin', 'form');
        if ($origin === 'ai') {
            return true;
        }

        $integration_settings = $this->sql->getItemValue($form_id, 'integration_settings', 'form');
        $settings = $this->maybeDecode($integration_settings);

        return is_array($settings) && is_array($settings['ai_draft'] ?? null);
    }

    private function ensureAiDraftState(int $form_id): void
    {
        if ($form_id <= 0 || $this->isAiDraftForm($form_id)) {
            return;
        }

        global $wpdb;

        $integration_settings = $this->sql->getItemValue($form_id, 'integration_settings', 'form');
        $settings = $this->maybeDecode($integration_settings);

        if (!is_array($settings)) {
            $settings = [];
        }

        $settings['ai_draft'] = [
            'prompt'             => '',
            'created_at'         => current_time('mysql', true),
            'session_id'         => wp_generate_uuid4(),
            'auto_start_pending' => 0,
            'origin'             => 'ai_edit',
        ];

        $wpdb->update(
            $this->config->getTable('form'),
            ['integration_settings' => maybe_serialize($settings)],
            ['id' => $form_id],
            ['%s'],
            ['%d']
        );
    }

    private function formTableHasColumn(string $column): bool
    {
        global $wpdb;

        $table = $this->config->getTable('form');
        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = %s AND COLUMN_NAME = %s",
            $table,
            $column
        ));

        return !empty($exists);
    }

    private function tabsJs()
    {
        echo '
        const gfRightSidebarTabs = $("#griffinforms-app-rightsidebar-tabs");
        if (gfRightSidebarTabs.length) {
            const formTab = gfRightSidebarTabs.find("[data-gf-tab=\'form\']");
            const elementTab = gfRightSidebarTabs.find("[data-gf-tab=\'element\']");
            const formPanel = $(".gf-rightsidebar-tabpanel[data-gf-tabpanel=\'form\']");
            const elementPanel = $(".gf-rightsidebar-tabpanel[data-gf-tabpanel=\'element\']");
            const elementLabel = elementTab.find(".gf-rightsidebar-tab-label");

            const notifyFormTabActive = () => {
                document.dispatchEvent(new CustomEvent("gf-rightsidebar-formtab-activated"));
            };

            const setActiveTab = (tab) => {
                const isElement = tab === "element";
                formTab.toggleClass("active", !isElement).attr("aria-selected", isElement ? "false" : "true");
                elementTab.toggleClass("active", isElement).attr("aria-selected", isElement ? "true" : "false");
                formPanel.toggle(!isElement);
                elementPanel.toggle(isElement);
                if (!isElement) {
                    notifyFormTabActive();
                }
                updateUnderline(isElement ? elementTab : formTab);
            };

            const getSelectedElement = () => {
                let selected = $("[data-gf-selected=true][data-gf-itemtype][data-gf-itemid]").first();
                if (!selected.length) {
                    const wrapper = $("[data-gf-selected=true]").first();
                    if (wrapper.length) {
                        selected = wrapper.find("[data-gf-itemtype][data-gf-itemid]").first();
                    }
                }
                return selected;
            };

            const getElementLabel = (itemType, selected) => {
                if (!itemType) return "' . esc_js(__('Element', 'griffinforms-form-builder')) . '";
                if (itemType === "field") {
                    return "' . esc_js(__('Field', 'griffinforms-form-builder')) . '";
                }
                const map = {
                    formpage: "' . esc_js(__('Page', 'griffinforms-form-builder')) . '",
                    pagerow: "' . esc_js(__('Row', 'griffinforms-form-builder')) . '",
                    rowcolumn: "' . esc_js(__('Column', 'griffinforms-form-builder')) . '",
                    form: "' . esc_js(__('Form', 'griffinforms-form-builder')) . '"
                };
                return map[itemType] || "' . esc_js(__('Element', 'griffinforms-form-builder')) . '";
            };

            const showElementTab = (label) => {
                elementLabel.text(label || "' . esc_js(__('Element', 'griffinforms-form-builder')) . '");
                elementTab.show();
                setActiveTab("element");
            };

            const hideElementTab = () => {
                elementTab.hide();
                setActiveTab("form");
            };

            formTab.on("click", function() {
                setActiveTab("form");
            });

            elementTab.on("click", function() {
                setActiveTab("element");
            });

            const updateUnderline = (tabEl) => {
                if (!tabEl || !tabEl.length) {
                    return;
                }
                const tabsOffset = gfRightSidebarTabs.offset();
                const tabOffset = tabEl.offset();
                if (!tabsOffset || !tabOffset) {
                    return;
                }
                const left = tabOffset.left - tabsOffset.left;
                const width = tabEl.outerWidth();
                gfRightSidebarTabs.css("--gf-tab-underline-left", left + "px");
                gfRightSidebarTabs.css("--gf-tab-underline-width", width + "px");
            };

            gfRightSidebarTabs.on("mouseenter", ".gf-rightsidebar-tab", function() {
                updateUnderline($(this));
            });

            gfRightSidebarTabs.on("mouseleave", function() {
                const activeTab = gfRightSidebarTabs.find(".gf-rightsidebar-tab.active");
                updateUnderline(activeTab);
            });

            const toggleAccordions = (expand = true) => {
                const activePanel = $(".gf-rightsidebar-tabpanel:visible");
                if (!activePanel.length) {
                    return;
                }
                activePanel.find(".accordion-collapse").each(function() {
                    const collapseEl = $(this);
                    if (typeof bootstrap !== "undefined" && typeof bootstrap.Collapse !== "undefined") {
                        const instance = bootstrap.Collapse.getOrCreateInstance(this, { toggle: false });
                        if (expand) {
                            instance.show();
                        } else {
                            instance.hide();
                        }
                    } else {
                        collapseEl.toggleClass("show", expand);
                        const button = collapseEl.prev(".accordion-header").find(".accordion-button");
                        button.toggleClass("collapsed", !expand);
                    }
                });
            };

            gfRightSidebarTabs.on("click", "[data-gf-accordion-action=\"expand\"]", function() {
                toggleAccordions(true);
            });

            gfRightSidebarTabs.on("click", "[data-gf-accordion-action=\"collapse\"]", function() {
                toggleAccordions(false);
            });

            document.addEventListener("item-selected", (event) => {
                const selected = getSelectedElement();
                const itemType = (event && event.detail && event.detail.itemType) ? event.detail.itemType : selected.attr("data-gf-itemtype");
                if (!itemType) {
                    hideElementTab();
                    return;
                }
                const label = getElementLabel(itemType, selected);
                showElementTab(label);
            });

            document.addEventListener("item-deselected", () => {
                hideElementTab();
            });

            hideElementTab();
            const activeTab = gfRightSidebarTabs.find(".gf-rightsidebar-tab.active");
            updateUnderline(activeTab);
        }
        ' . PHP_EOL;
    }

    private function itemSelectedEventListenerJs()
    {
        echo '
        document.addEventListener("item-selected", () => {

            const selectedItem = $("[data-gf-selected=true]");
            showItemOptions(selectedItem);
        });
        ' . PHP_EOL;
    }
}
