<?php

namespace WPSN\Admin;

use WPSN\Modules\TasksHub\TaskWorkbenchQueueRepository;

defined('ABSPATH') || exit;

/**
 * Shows a lightweight return banner when users open WPSN admin screens from
 * a Tasks Hub queue.
 */
final class TasksReturnContextNotice
{
    public function register(): void
    {
        add_action('admin_notices', [$this, 'render']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
    }

    public function enqueueAssets(): void
    {
        if (!is_admin()) {
            return;
        }

        $page = isset($_GET['page']) ? sanitize_key((string) wp_unslash($_GET['page'])) : '';
        if (!$this->supportsPage($page)) {
            return;
        }

        $context = TasksWorkbenchContext::requestArgs(true);
        if ($context === []) {
            return;
        }

        wp_enqueue_script(
            'wpsn-task-workbench-context',
            WPSN_PLUGIN_URL . 'assets/admin/task-workbench-context.js',
            [],
            WPSN_VERSION,
            true
        );

        wp_localize_script('wpsn-task-workbench-context', 'WPSN_TaskWorkbenchContext', [
            'enabled' => true,
            'returnTo' => isset($context['return_to']) ? (string) $context['return_to'] : '',
            'queueTitle' => isset($context['wpsn_task_queue_title']) ? (string) $context['wpsn_task_queue_title'] : '',
            'snapshotKey' => isset($context['wpsn_task_queue_key']) ? (string) $context['wpsn_task_queue_key'] : '',
            'taskRef' => isset($context['wpsn_task_ref']) ? (string) $context['wpsn_task_ref'] : '',
        ]);
    }

    public function render(): void
    {
        if (!is_admin()) {
            return;
        }

        $page = isset($_GET['page']) ? sanitize_key((string) wp_unslash($_GET['page'])) : '';
        if (!$this->supportsPage($page)) {
            return;
        }

        $context = TasksWorkbenchContext::requestArgs(true);
        $returnTo = isset($context['return_to']) ? (string) $context['return_to'] : '';
        $queueTitle = isset($context['wpsn_task_queue_title']) ? (string) $context['wpsn_task_queue_title'] : '';
        $snapshotKey = isset($context['wpsn_task_queue_key']) ? (string) $context['wpsn_task_queue_key'] : '';
        $taskRef = isset($context['wpsn_task_ref']) ? (string) $context['wpsn_task_ref'] : '';

        if ($snapshotKey !== '' && $taskRef !== '') {
            $nav = $this->queueRepository()->navigation($snapshotKey, $taskRef);
            if ((int) ($nav['total'] ?? 0) > 0 && (int) ($nav['position'] ?? 0) > 0) {
                $returnTo = $returnTo !== '' ? $returnTo : (string) ($nav['return_to'] ?? '');
                $queueTitle = $queueTitle !== '' ? $queueTitle : (string) ($nav['queue_title'] ?? '');
                $this->renderQueueNavigationNotice($nav, $snapshotKey, $queueTitle, $returnTo);
                return;
            }
        }

        if ($returnTo === '') {
            return;
        }

        if ($queueTitle === '') {
            $queueTitle = __('Tasks Hub context', 'wp-seo-next');
        }

        echo '<div class="notice notice-info">';
        echo '<p><strong>' . esc_html($queueTitle) . '</strong> — ' . esc_html__('You opened this screen from Tasks Hub. Use the button below to return to the same working queue.', 'wp-seo-next') . '</p>';
        echo '<p><a class="button button-secondary" href="' . esc_url($returnTo) . '">' . esc_html__('Back to Tasks', 'wp-seo-next') . '</a></p>';
        echo '</div>';
    }

    public function supportsPage(string $page): bool
    {
        $page = sanitize_key($page);
        if ($page === '' || $page === 'wpsn-tasks') {
            return false;
        }

        return $page === 'wp-seo-next' || strpos($page, 'wpsn-') === 0;
    }

    /**
     * @param array{queue_title:string,return_to:string,total:int,position:int,current:array<string,mixed>,prev:array<string,mixed>,next:array<string,mixed>} $nav
     */
    private function renderQueueNavigationNotice(array $nav, string $snapshotKey, string $queueTitle, string $returnTo): void
    {
        $current = isset($nav['current']) && is_array($nav['current']) ? $nav['current'] : [];
        $prev = isset($nav['prev']) && is_array($nav['prev']) ? $nav['prev'] : [];
        $next = isset($nav['next']) && is_array($nav['next']) ? $nav['next'] : [];
        $position = (int) ($nav['position'] ?? 0);
        $total = (int) ($nav['total'] ?? 0);

        if ($queueTitle === '') {
            $queueTitle = __('Tasks Hub context', 'wp-seo-next');
        }

        $currentLabel = isset($current['label']) ? sanitize_text_field((string) $current['label']) : '';
        $prevUrl = $this->queueRepository()->itemUrl($snapshotKey, $prev);
        $nextUrl = $this->queueRepository()->itemUrl($snapshotKey, $next);

        echo '<div class="notice notice-info">';
        echo '<p><strong>' . esc_html($queueTitle) . '</strong>';
        if ($position > 0 && $total > 0) {
            echo ' — ' . esc_html(sprintf(__('Task %1$d of %2$d', 'wp-seo-next'), $position, $total));
        }
        if ($currentLabel !== '') {
            echo ': ' . esc_html($currentLabel);
        }
        echo '</p>';
        echo '<p>' . esc_html__('You opened this screen from Tasks Hub. Move through the same queue or jump back to the originating workspace.', 'wp-seo-next') . '</p>';
        echo '<p style="display:flex; gap:6px; flex-wrap:wrap; align-items:center;">';
        if ($prevUrl !== '') {
            echo '<a class="button button-secondary" href="' . esc_url($prevUrl) . '">' . esc_html__('Previous task', 'wp-seo-next') . '</a>';
        }
        if ($nextUrl !== '') {
            echo '<a class="button button-primary" href="' . esc_url($nextUrl) . '">' . esc_html__('Next task', 'wp-seo-next') . '</a>';
        }
        if ($returnTo !== '') {
            echo '<a class="button button-secondary" href="' . esc_url($returnTo) . '">' . esc_html__('Back to Tasks', 'wp-seo-next') . '</a>';
        }
        echo '</p>';
        echo '</div>';
    }

    private function queueRepository(): TaskWorkbenchQueueRepository
    {
        return new TaskWorkbenchQueueRepository($this->currentUserId());
    }

    private function currentUserId(): int
    {
        return function_exists('get_current_user_id') ? max(0, (int) get_current_user_id()) : 0;
    }

    private function sanitizeTaskRef(string $ref): string
    {
        $ref = trim($ref);
        if ($ref === '') {
            return '';
        }

        $ref = preg_replace('/[^a-zA-Z0-9:_\-]/', '', $ref);
        return is_string($ref) ? $ref : '';
    }
}
