<?php

namespace WPSN\Admin;

use WPSN\Core\Capabilities;
use WPSN\Core\Container;
use WPSN\Modules\AI\AISecretsRepository;
use WPSN\Modules\SerpGap\SerpSecretsRepository;
use WPSN\Modules\SiteKit\Admin\SiteKitAdmin;

defined('ABSPATH') || exit;

/**
 * Connections / Setup Hub.
 *
 * Goal:
 * - One place to see what is connected and what is missing.
 * - No heavy AJAX; only status + direct links.
 * - Keep wording similar to Yoast: the underlying connector is only mentioned for installation.
 */
final class ConnectionsAdmin
{
    public const PAGE_SLUG = 'wpsn-connections';

    private Container $container;

    /** @var mixed */
    private $settings;

    /** @var string|null */
    private ?string $hookSuffix = null;

    public function __construct(Container $container)
    {
        $this->container = $container;
        $this->settings = $container->get('settings');
    }

    public function register(): void
    {
        add_action('admin_menu', [$this, 'addMenu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
    }

    public function addMenu(): void
    {
        $this->hookSuffix = add_management_page(
            __('Connections', 'wp-seo-next'),
            __('Connections', 'wp-seo-next'),
            Capabilities::CAP_TOOLS,
            self::PAGE_SLUG,
            [$this, 'render']
        );
    }

    public function enqueueAssets(string $hookSuffix): void
    {
        if ($this->hookSuffix === null || $hookSuffix !== $this->hookSuffix) {
            return;
        }

        // Reuse Search Insights admin styling (cards, tables, etc.).
        wp_enqueue_style(
            'wpsn-sitekit-admin',
            WPSN_PLUGIN_URL . 'assets/admin/sitekit.css',
            [],
            WPSN_VERSION
        );
    }

    private function toolsUrl(string $pageSlug): string
    {
        return admin_url('tools.php?page=' . sanitize_key($pageSlug));
    }

    public function render(): void
    {
        if (!Capabilities::canManageTools()) {
            wp_die(esc_html__('You do not have permission to access this page.', 'wp-seo-next'));
        }

        $searchInsightsUrl = $this->toolsUrl(SiteKitAdmin::PAGE_SLUG);
        $gscUrl = $this->toolsUrl('wpsn-search-console');
        $serpUrl = $this->toolsUrl('wpsn-serp-gap');
        $settingsUrl = admin_url('admin.php?page=wp-seo-next');

        echo '<div class="wrap wpsn-sitekit">';
        echo '<h1>' . esc_html__('Connections', 'wp-seo-next') . '</h1>';
        echo '<p class="description">' . esc_html__('Check integration status and complete setup steps. This page avoids heavy background requests and only shows status + direct links.', 'wp-seo-next') . '</p>';

        echo '<div class="wpsn-sk-grid">';

        // 1) Google data connector (Search Insights)
        $this->renderGoogleDataCard($searchInsightsUrl);

        // 2) Search Console API module (our own)
        $this->renderSearchConsoleCard($gscUrl);

        // 3) External AI
        $this->renderAICard($settingsUrl);

        // 4) SERP provider
        $this->renderSerpCard($serpUrl, $settingsUrl);

        // 5) Queue mode
        $this->renderQueueCard($settingsUrl);

        echo '</div>'; // grid

        echo '</div>';
    }

    private function renderGoogleDataCard(string $searchInsightsUrl): void
    {
        $enabled = (bool) $this->settings->moduleEnabled('site_kit', true);
        $disableInstallHelper = (bool) $this->settings->get('privacy.disable_sitekit_install_helper', false);

        echo '<div class="wpsn-sk-widget">';
        echo '<h3>' . esc_html__('Google data (Search Insights)', 'wp-seo-next') . '</h3>';

        if (!$enabled) {
            echo '<p class="description">' . esc_html__('Search Insights module is disabled. Enable it in Settings → Modules.', 'wp-seo-next') . '</p>';
            echo '<p><a class="button button-secondary" href="' . esc_url(admin_url('admin.php?page=wp-seo-next&wpsn_focus_module=site_kit')) . '">' . esc_html__('Open Settings', 'wp-seo-next') . '</a></p>';
            echo '</div>';
            return;
        }

        $sk = new SiteKitAdmin($this->container);
        $status = $sk->getStatus();

        $installed = (bool) ($status['installed'] ?? false);
        $active = (bool) ($status['active'] ?? false);
        $setup = (bool) ($status['setupComplete'] ?? false);
        $consent = (bool) ($status['consent'] ?? false);

        echo '<ul style="margin:10px 0 12px 18px; list-style: disc;">';
        echo '<li>' . esc_html__('Installed:', 'wp-seo-next') . ' <strong>' . esc_html($installed ? __('Yes', 'wp-seo-next') : __('No', 'wp-seo-next')) . '</strong></li>';
        echo '<li>' . esc_html__('Active:', 'wp-seo-next') . ' <strong>' . esc_html($active ? __('Yes', 'wp-seo-next') : __('No', 'wp-seo-next')) . '</strong></li>';
        echo '<li>' . esc_html__('Google setup:', 'wp-seo-next') . ' <strong>' . esc_html($setup ? __('Complete', 'wp-seo-next') : __('Not complete', 'wp-seo-next')) . '</strong></li>';
        echo '<li>' . esc_html__('Connected:', 'wp-seo-next') . ' <strong>' . esc_html($consent ? __('Yes', 'wp-seo-next') : __('No', 'wp-seo-next')) . '</strong></li>';
        echo '</ul>';

        // Actions (only mention Site Kit for the installation step).
        echo '<div style="display:flex; gap:8px; flex-wrap:wrap;">';

        echo '<a class="button button-secondary" href="' . esc_url($searchInsightsUrl) . '">' . esc_html__('Open Search Insights', 'wp-seo-next') . '</a>';

        if ($disableInstallHelper && (!$installed || ($installed && !$active))) {
            echo '<p class="description">' . esc_html__('Install/activate helper is disabled by Trust/Privacy policy. Please install/activate the required Google connector plugin from Plugins → Add New, then return here.', 'wp-seo-next') . '</p>';
        } elseif (!$installed) {
            echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" style="display:inline-block; margin:0;">';
            echo '<input type="hidden" name="action" value="wpsn_sitekit_install" />';
            wp_nonce_field('wpsn_sitekit_install');
            echo '<button type="submit" class="button button-primary">' . esc_html__('Install Google Site Kit', 'wp-seo-next') . '</button>';
            echo '</form>';
        } elseif ($installed && !$active) {
            echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" style="display:inline-block; margin:0;">';
            echo '<input type="hidden" name="action" value="wpsn_sitekit_activate" />';
            wp_nonce_field('wpsn_sitekit_activate');
            echo '<button type="submit" class="button button-primary">' . esc_html__('Activate connector', 'wp-seo-next') . '</button>';
            echo '</form>';
        } elseif ($active && !$setup) {
            echo '<a class="button button-primary" target="_blank" rel="noopener noreferrer" href="' . esc_url(admin_url('admin.php?page=googlesitekit-dashboard')) . '">' . esc_html__('Open Google setup', 'wp-seo-next') . '</a>';
        } elseif ($setup && !$consent) {
            if ($disableInstallHelper) {
                echo '<p class="description">' . esc_html__('Consent helper is disabled by Trust/Privacy policy. Please open Google setup and complete consent there.', 'wp-seo-next') . '</p>';
            } else {
                echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" style="display:inline-block; margin:0;">';
                echo '<input type="hidden" name="action" value="wpsn_sitekit_consent" />';
                wp_nonce_field('wpsn_sitekit_consent');
                echo '<button type="submit" class="button button-primary">' . esc_html__('Grant consent', 'wp-seo-next') . '</button>';
                echo '</form>';
            }
        }

        echo '</div>';

        echo '</div>';
    }

    private function renderSearchConsoleCard(string $gscUrl): void
    {
        $enabled = (bool) $this->settings->moduleEnabled('search_console', true);
        $property = (string) $this->settings->get('search_console.property', '');
        $property = trim($property);

        echo '<div class="wpsn-sk-widget">';
        echo '<h3>' . esc_html__('Search Console API', 'wp-seo-next') . '</h3>';
        echo '<p class="description">' . esc_html__('Used for rank tracking, briefs, and internal link suggestions.', 'wp-seo-next') . '</p>';

        if (!$enabled) {
            echo '<p><strong>' . esc_html__('Status:', 'wp-seo-next') . '</strong> ' . esc_html__('Disabled', 'wp-seo-next') . '</p>';
            echo '<p><a class="button button-secondary" href="' . esc_url(admin_url('admin.php?page=wp-seo-next&wpsn_focus_module=search_console')) . '">' . esc_html__('Open Settings', 'wp-seo-next') . '</a></p>';
            echo '</div>';
            return;
        }

        if ($property !== '') {
            echo '<p><strong>' . esc_html__('Status:', 'wp-seo-next') . '</strong> <span style="color:#0a7; font-weight:600;">' . esc_html__('Configured', 'wp-seo-next') . '</span></p>';
            echo '<p class="description">' . esc_html__('Property:', 'wp-seo-next') . ' <code>' . esc_html($property) . '</code></p>';
        } else {
            echo '<p><strong>' . esc_html__('Status:', 'wp-seo-next') . '</strong> <span style="color:#a00; font-weight:600;">' . esc_html__('Not configured', 'wp-seo-next') . '</span></p>';
            echo '<p class="description">' . esc_html__('Pick a property and complete authorization to enable briefs and internal link suggestions.', 'wp-seo-next') . '</p>';
        }

        echo '<p><a class="button button-secondary" href="' . esc_url($gscUrl) . '">' . esc_html__('Open Search Console', 'wp-seo-next') . '</a></p>';
        echo '</div>';
    }

    private function renderAICard(string $settingsUrl): void
    {
        $externalEnabled = (bool) $this->settings->get('ai.external.enabled', false);
        $provider = sanitize_key((string) $this->settings->get('ai.external.provider', 'openai'));
        if ($provider === '') {
            $provider = 'openai';
        }
        if (!in_array($provider, ['openai', 'saas_proxy'], true)) {
            $provider = 'openai';
        }

        $hasKey = (new AISecretsRepository())->hasOpenAIKey();
        $localOnly = (bool) $this->settings->get('privacy.local_only', false);

        echo '<div class="wpsn-sk-widget">';
        echo '<h3>' . esc_html__('AI', 'wp-seo-next') . '</h3>';
        echo '<p class="description">' . esc_html__('Used for editor autofill, briefs, SERP gap outlines, and bulk tools.', 'wp-seo-next') . '</p>';

        echo '<p><strong>' . esc_html__('External AI:', 'wp-seo-next') . '</strong> ' . esc_html($externalEnabled ? __('Enabled', 'wp-seo-next') : __('Disabled', 'wp-seo-next')) . '</p>';
        echo '<p><strong>' . esc_html__('Provider:', 'wp-seo-next') . '</strong> <code>' . esc_html($provider) . '</code></p>';

        if ($provider === 'openai') {
            echo '<p><strong>' . esc_html__('OpenAI key:', 'wp-seo-next') . '</strong> ' . ($hasKey ? '<span style="color:#0a7; font-weight:600;">' . esc_html__('Set', 'wp-seo-next') . '</span>' : '<span style="color:#a00; font-weight:600;">' . esc_html__('Missing', 'wp-seo-next') . '</span>') . '</p>';
        }

        if ($localOnly) {
            echo '<p class="description">' . esc_html__('Local-only mode is enabled. External AI requests are blocked.', 'wp-seo-next') . '</p>';
        }

        echo '<p><a class="button button-secondary" href="' . esc_url($settingsUrl) . '">' . esc_html__('Open Settings', 'wp-seo-next') . '</a></p>';
        echo '</div>';
    }

    private function renderSerpCard(string $serpUrl, string $settingsUrl): void
    {
        $provider = sanitize_key((string) $this->settings->get('serp_gap.provider_id', 'manual'));
        if ($provider === '') {
            $provider = 'manual';
        }

        $hasKey = false;
        if ($provider === 'serper') {
            $hasKey = (new SerpSecretsRepository())->hasSerperKey();
        }

        echo '<div class="wpsn-sk-widget">';
        echo '<h3>' . esc_html__('SERP provider', 'wp-seo-next') . '</h3>';
        echo '<p class="description">' . esc_html__('Used for SERP gap and competitor analysis.', 'wp-seo-next') . '</p>';

        echo '<p><strong>' . esc_html__('Provider:', 'wp-seo-next') . '</strong> <code>' . esc_html($provider) . '</code></p>';

        if ($provider === 'manual') {
            echo '<p class="description">' . esc_html__('Manual mode is enabled. SERP gap will require manual SERP input.', 'wp-seo-next') . '</p>';
        } elseif ($provider === 'serper') {
            echo '<p><strong>' . esc_html__('API key:', 'wp-seo-next') . '</strong> ' . ($hasKey ? '<span style="color:#0a7; font-weight:600;">' . esc_html__('Set', 'wp-seo-next') . '</span>' : '<span style="color:#a00; font-weight:600;">' . esc_html__('Missing', 'wp-seo-next') . '</span>') . '</p>';
        }

        echo '<p style="display:flex; gap:8px; flex-wrap:wrap;">';
        echo '<a class="button button-secondary" href="' . esc_url($serpUrl) . '">' . esc_html__('Open SERP Gap tool', 'wp-seo-next') . '</a>';
        echo '<a class="button button-secondary" href="' . esc_url($settingsUrl) . '">' . esc_html__('Open Settings', 'wp-seo-next') . '</a>';
        echo '</p>';

        echo '</div>';
    }

    private function renderQueueCard(string $settingsUrl): void
    {
        $mode = sanitize_key((string) $this->settings->get('performance.queue.mode', 'auto'));
        if ($mode === '') {
            $mode = 'auto';
        }

        echo '<div class="wpsn-sk-widget">';
        echo '<h3>' . esc_html__('Queue', 'wp-seo-next') . '</h3>';
        echo '<p class="description">' . esc_html__('Controls how background jobs run on your hosting.', 'wp-seo-next') . '</p>';

        echo '<p><strong>' . esc_html__('Mode:', 'wp-seo-next') . '</strong> <code>' . esc_html($mode) . '</code></p>';
        echo '<p class="description">' . esc_html__('Tip: If WP-Cron is unreliable on your host, use Direct (no cron).', 'wp-seo-next') . '</p>';

        echo '<p><a class="button button-secondary" href="' . esc_url($settingsUrl) . '">' . esc_html__('Open Settings', 'wp-seo-next') . '</a></p>';
        echo '</div>';
    }
}
