<?php

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

final class RecentSubmissions extends \GriffinForms\Admin\App\Html\Widgets\RightSidebar\Format
{
    protected $form_id;
    protected $recent_submissions = array();

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

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

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

    private function refreshSubmissionsJs()
    {
        $nonce = wp_create_nonce('recent_submissions');
        $placeholder_html = $this->getPlaceholderSkeleton();

        echo '
        const refreshRecentSubmissionsWidget = () => {
            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_html) . '`);

            const data = {
                "action": "getRecentSubmissionsContent",
                "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 recent submissions. Please try again.', 'griffinforms-form-builder')) . '</div>");
                $("#' . esc_attr($this->getHtmlId('spinner')) . '").hide();
            });
        };

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

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

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

        refreshRecentSubmissionsWidget();
        ' . PHP_EOL;
    }

    public function getRecentSubmissionsContent()
    {
        $this->checkRequest('recent_submissions');

        $this->form_id = isset($_POST['form_id']) ? absint(wp_unslash($_POST['form_id'])) : 0;
        if (!$this->form_id) {
            $this->errorMessage(__('Invalid form ID.', 'griffinforms-form-builder'));
            wp_die();
        }

        if (!$this->sql->itemExists('form', $this->form_id)) {
            $this->errorMessage(__('Form not found.', 'griffinforms-form-builder'));
            wp_die();
        }

        $this->recent_submissions = $this->sql->getRecentFormSubmissions($this->form_id, 5);

        if (empty($this->recent_submissions)) {
            $this->emptyState();
        } else {
            $this->submissionList();
        }

        wp_die();
    }

    protected function submissionList()
    {
        echo '<div class="list-group p-3 pb-4 small">';

        foreach ($this->recent_submissions as $submission) {
            $this->submissionItem($submission);
        }

        echo '</div>';
    }

    protected function submissionItem($submission)
    {
        $submission_id = isset($submission['id']) ? absint($submission['id']) : 0;
        $author = $submission['author'] ?? 0;
        $created = $submission['created'] ?? '';
        $status = isset($submission['status']) ? absint($submission['status']) : 0;

        $display_name = $this->sql->getSubmissionDisplayName($submission_id);
        $author_name = $this->getAuthorName($author);
        $date_formatted = $created ? wp_date($this->config->getDateTimeFormat(), strtotime($created)) : '';
        $submission_url = admin_url('admin.php?page=griffinforms-submission&id=' . $submission_id);

        echo '<a href="' . esc_url($submission_url) . '" target="_blank" rel="noopener noreferrer" class="list-group-item list-group-item-action px-3 py-2 text-decoration-none" style="color: inherit; cursor: pointer;">';
        echo '<div class="d-flex justify-content-between align-items-start">';

        echo '<div class="flex-grow-1 me-2">';
        echo '<div class="fw-medium mb-1 d-flex align-items-start" style="word-break: break-word;">';
        echo '<span class="flex-grow-1">' . esc_html($display_name) . '</span>';
        echo '</div>';

        echo '<div class="text-secondary small">';
        echo '<span class="me-1">' . esc_html($author_name) . '</span>';
        if ($date_formatted !== '') {
            echo '•';
            echo '<span class="ms-1">' . esc_html($date_formatted) . '</span>';
        }
        echo '</div>';
        echo '</div>';

        echo '<div>'; 
        if ($status) {
            echo '<span class="badge text-bg-success">' . esc_html__('Complete', 'griffinforms-form-builder') . '</span>';
        } else {
            echo '<span class="badge text-bg-secondary">' . esc_html__('Incomplete', 'griffinforms-form-builder') . '</span>';
        }
        echo '</div>';

        echo '</div>';
        echo '</a>';
    }

    protected function emptyState()
    {
        echo '<div class="gf-log-empty text-muted small p-3">';
        echo esc_html__('No submissions recorded for this form yet.', 'griffinforms-form-builder');
        echo '</div>';
    }

    protected function getAuthorName($author_id)
    {
        $author_id = absint($author_id);
        if (!$author_id) {
            return __('Unknown', 'griffinforms-form-builder');
        }

        $user = get_user_by('id', $author_id);
        if ($user === false) {
            return __('Unknown', 'griffinforms-form-builder');
        }

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

        return $user->display_name;
    }

    protected function getPlaceholderSkeleton()
    {
        ob_start();
        echo '<div class="list-group p-3">';

        for ($i = 0; $i < 5; $i++) {
            echo '<div class="list-group-item px-3 py-2">';
            echo '<div class="d-flex justify-content-between align-items-start">';

            echo '<div class="flex-grow-1 me-2">';
            echo '<div class="mb-2 d-flex align-items-start">';
            echo '<span class="placeholder col-8 bg-secondary"></span>';
            echo '</div>';
            echo '<div class="d-flex align-items-center gap-2">';
            echo '<span class="placeholder col-3 bg-secondary" style="height: 14px;"></span>';
            echo '<span class="bg-secondary" style="width: 4px; height: 4px; border-radius: 50%; display: inline-block;"></span>';
            echo '<span class="placeholder col-4 bg-secondary" style="height: 14px;"></span>';
            echo '</div>';
            echo '</div>';

            echo '<span class="placeholder col-3 bg-secondary" style="height: 18px;"></span>';

            echo '</div>';
            echo '</div>';
        }

        echo '</div>';
        return ob_get_clean();
    }

    protected function errorMessage($message)
    {
        echo '<div class="alert alert-danger m-2" role="alert">';
        echo esc_html($message);
        echo '</div>';
    }

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