<?php

namespace GriffinForms\Admin\App\Html\Widgets\RightSidebar;

use GriffinForms\Includes\Integrations\FormSettingsManager;

final class FormSummary extends \GriffinForms\Admin\App\Html\Widgets\RightSidebar\Format
{
    protected $form;

    public function getHtml()
    {
        $title = __('Summary', 'griffinforms-form-builder');
        $this->accordionHtml($title);
    }

    protected function accordionBody()
    {
        echo $this->getPlaceholderHtml();
    }

    public function widgetJs()
    {
        $this->refreshSummaryJs();
    }

    private function refreshSummaryJs()
    {
        $nonce = wp_create_nonce('form_summary_widget');
        $placeholder = $this->getPlaceholderHtml();

        echo '
        const refreshFormSummaryWidget = () => {
            const formElement = $("#griffinforms-app-presentationarea").find("[data-gf-itemtype=form]");
            const formId = formElement.attr("data-gf-itemid");
            if (!formId) {
                $("#' . esc_attr($this->getHtmlId()) . '").hide();
                return;
            }

            $("#' . esc_attr($this->getHtmlId()) . '").show();
            $("#' . esc_attr($this->getHtmlId('spinner')) . '").show();
            $("#' . esc_attr($this->getHtmlId('content')) . '").find(".accordion-body").html(`' . addslashes($placeholder) . '`);

            const data = {
                "action": "getFormSummaryWidgetContent",
                "form_id": formId,
                "nonce": "' . esc_js($nonce) . '"
            };

            $.post(ajaxurl, data, function(response) {
                $("#' . esc_attr($this->getHtmlId('content')) . '").find(".accordion-body").html(response);
                $("#' . esc_attr($this->getHtmlId('spinner')) . '").hide();
            }).fail(function() {
                $("#' . esc_attr($this->getHtmlId('content')) . '").find(".accordion-body").html("<div class=\"gf-notice gf-notice-danger\">' . esc_js(__('Failed to load form summary. Please try again.', 'griffinforms-form-builder')) . '</div>");
                $("#' . esc_attr($this->getHtmlId('spinner')) . '").hide();
            });
        };

        document.addEventListener("gf-rightsidebar-formtab-activated", () => {
            refreshFormSummaryWidget();
        });

        document.addEventListener("form-updated", () => {
            refreshFormSummaryWidget();
        });

        document.addEventListener("form-html-received", () => {
            refreshFormSummaryWidget();
        });

        refreshFormSummaryWidget();
        ' . PHP_EOL;
    }

    public function getFormSummaryWidgetContent()
    {
        $this->checkRequest('form_summary_widget');

        $form_id = isset($_POST['form_id']) ? absint(wp_unslash($_POST['form_id'])) : 0;
        if (!$form_id) {
            echo '<div class="gf-notice gf-notice-danger">' . esc_html__('Invalid form ID.', 'griffinforms-form-builder') . '</div>';
            wp_die();
        }

        $this->form = $this->sql->itemValues($form_id, 'form');
        if (!$this->form) {
            echo '<div class="gf-notice gf-notice-danger">' . esc_html__('Form not found.', 'griffinforms-form-builder') . '</div>';
            wp_die();
        }

        $this->renderSummary();
        wp_die();
    }

    private function renderSummary()
    {
        echo '<div class="p-3">';
        $this->propRow(__('ID', 'griffinforms-form-builder'), $this->form->id ?? '');
        $this->propRow(__('Name', 'griffinforms-form-builder'), $this->form->name ?? '');
        $this->propRow(__('Description', 'griffinforms-form-builder'), $this->form->description ?? '');
        $this->propRow(__('Created By', 'griffinforms-form-builder'), $this->getCreatedByName());
        $this->propRow(__('Created On', 'griffinforms-form-builder'), $this->getCreatedOn());
        $this->propRow(__('Theme', 'griffinforms-form-builder'), $this->getThemeLinkHtml(), true);
        $this->propRow(__('Folder', 'griffinforms-form-builder'), $this->getFolderLinkHtml(), true);
        $this->propRow(__('Submissions', 'griffinforms-form-builder'), $this->getSubmissionCountLink(), true);
        $this->propRow(str_replace(' ', "\xc2\xa0", __('User Registration', 'griffinforms-form-builder')), $this->getUserRegistrationLinkHtml(), true);
        $this->propRow(__('Shortcode', 'griffinforms-form-builder'), $this->getShortcodeHtml(), true);
        echo '</div>';
    }

    private function getPlaceholderHtml()
    {
        ob_start();
        echo '<div class="p-3">';
        for ($i = 0; $i < 5; $i++) {
            echo '<div class="row mb-2 small align-items-center">';
            echo '<div class="col-md-4 fw-semibold mb-1">';
            echo '<span class="placeholder col-8 bg-secondary"></span>';
            echo '</div>';
            echo '<div class="col-md-8">';
            echo '<span class="placeholder col-10 bg-secondary"></span>';
            echo '</div>';
            echo '</div>';
        }
        echo '</div>';
        return ob_get_clean();
    }

    private function getSubmissionCount()
    {
        if (isset($this->form->lifetime_submission_count) && is_numeric($this->form->lifetime_submission_count)) {
            return (int) $this->form->lifetime_submission_count;
        }
        return (int) $this->sql->submissionCount($this->form->id, 1);
    }

    private function getUserRegistrationSummary()
    {
        $form_id = isset($this->form->id) ? absint($this->form->id) : 0;
        if (!$form_id) {
            return __('Not configured', 'griffinforms-form-builder');
        }

        $stored = FormSettingsManager::getInstance()->getIntegrationSettings($form_id, 'wordpress_accounts');
        $settings = is_array($stored) ? ($stored['settings'] ?? []) : [];
        $setups = is_array($settings) ? ($settings['rules'] ?? []) : [];
        $setups = is_array($setups) ? array_values(array_filter($setups, 'is_array')) : [];
        $count = count($setups);

        if ($count < 1) {
            return __('Not configured', 'griffinforms-form-builder');
        }

        if ($count === 1) {
            return __('1 workflow', 'griffinforms-form-builder');
        }

        return sprintf(
            /* translators: %d is the number of configured user registration workflows. */
            __('%d workflows', 'griffinforms-form-builder'),
            $count
        );
    }

    private function getUserRegistrationLinkHtml()
    {
        $label = $this->getUserRegistrationSummary();
        return '<a href="#" class="gf-text-primary text-decoration-none" data-bs-toggle="modal" data-bs-target="#griffinforms-builder-modal-accounts">' . esc_html($label) . '</a>';
    }

    private function getSubmissionCountLink()
    {
        $count = $this->getSubmissionCount();
        $url = admin_url('admin.php?page=griffinforms-submissions&form_id=' . absint($this->form->id));
        return '<a href="' . esc_url($url) . '" class="text-decoration-none gf-text-primary" target="_blank" rel="noopener noreferrer">' . esc_html($count) . '</a>';
    }

    private function getThemeName()
    {
        return $this->sql->getFormThemeName($this->form->id ?? 0);
    }

    private function getThemeLinkHtml()
    {
        $label = $this->getThemeName();
        return '<a href="#" class="gf-text-primary text-decoration-none" data-bs-toggle="modal" data-bs-target="#griffinforms-builder-modal-formthemes">' . esc_html($label) . '</a>';
    }

    private function getFolderName()
    {
        return $this->sql->getFormFolderName($this->form->id ?? 0);
    }

    private function getFolderId()
    {
        return absint($this->form->folder ?? 0);
    }

    private function getFolderLinkHtml()
    {
        $label = $this->getFolderName();
        return '<span class="gf-form-folder-link">' . esc_html($label) . '</span>';
    }

    private function getShortcodeHtml()
    {
        $shortcode = '[griffinforms_form id=' . absint($this->form->id) . ']';
        return '<span class="gf-shortcode-pill">' . esc_html($shortcode) . '</span>';
    }

    private function getCreatedByName()
    {
        $user_id = isset($this->form->author) ? absint($this->form->author) : 0;
        if (!$user_id) {
            return __('User not found', 'griffinforms-form-builder');
        }

        $user = get_user_by('id', $user_id);
        if ($user === false) {
            return __('User not found', 'griffinforms-form-builder');
        }

        $display_name = $user->display_name;
        if ($user_id === get_current_user_id()) {
            return sprintf(__('Me – %s', 'griffinforms-form-builder'), $display_name);
        }

        return $display_name;
    }

    private function getCreatedOn()
    {
        $created = $this->form->created ?? '';
        if (!$created) {
            return '';
        }

        return wp_date($this->config->getDateTimeFormat(), strtotime($created));
    }

    public function __construct()
    {
        $this->setAll();
        add_action('wp_ajax_getFormSummaryWidgetContent', array($this, 'getFormSummaryWidgetContent'));
    }
}
