<?php

namespace Datalumo\Admin;

class SettingsPage
{
    private string $hookSuffix = '';

    public function __construct()
    {
        add_action('admin_menu', [$this, 'addMenuPage']);
        add_action('admin_init', [$this, 'registerSettings']);
    }

    public function addMenuPage(): void
    {
        $this->hookSuffix = add_options_page(
            __('Datalumo', 'datalumo'),
            __('Datalumo', 'datalumo'),
            'manage_options',
            'datalumo',
            [$this, 'renderPage']
        );

        if ($this->hookSuffix) {
            add_action("admin_enqueue_scripts", [$this, 'enqueueAssets']);
        }
    }

    public function registerSettings(): void
    {
        // API key is saved via AJAX now, but we still register it
        // so WordPress recognizes it as a valid option.
        register_setting('datalumo_settings', 'datalumo_api_key', [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ]);

        // Content Sync tab
        register_setting('datalumo_content_sync_settings', 'datalumo_content_syncs', [
            'type'              => 'array',
            'sanitize_callback' => [$this, 'sanitizeContentSyncs'],
            'default'           => [],
        ]);

        // Chatbot tab
        register_setting('datalumo_chatbot_settings', 'datalumo_chatbot_enabled', [
            'type'              => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default'           => false,
        ]);

        register_setting('datalumo_chatbot_settings', 'datalumo_chatbot_integration_id', [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ]);

        register_setting('datalumo_chatbot_settings', 'datalumo_chatbot_mode', [
            'type'              => 'string',
            'sanitize_callback' => [$this, 'sanitizeChatbotMode'],
            'default'           => 'popup',
        ]);

        register_setting('datalumo_chatbot_settings', 'datalumo_chatbot_popup_position', [
            'type'              => 'string',
            'sanitize_callback' => [$this, 'sanitizeChatbotPopupPosition'],
            'default'           => 'bottom-right',
        ]);

        register_setting('datalumo_chatbot_settings', 'datalumo_chatbot_sidebar_side', [
            'type'              => 'string',
            'sanitize_callback' => [$this, 'sanitizeChatbotSidebarSide'],
            'default'           => 'right',
        ]);

        register_setting('datalumo_chatbot_settings', 'datalumo_chatbot_sidebar_push', [
            'type'              => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default'           => false,
        ]);

        register_setting('datalumo_chatbot_settings', 'datalumo_chatbot_show_avatar', [
            'type'              => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default'           => true,
        ]);

        // Search Box tab
        register_setting('datalumo_search_box_settings', 'datalumo_search_box_integration_id', [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ]);

        // Enhanced Native Search tab
        register_setting('datalumo_search_settings', 'datalumo_search_enhanced', [
            'type'              => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default'           => false,
        ]);

        register_setting('datalumo_search_settings', 'datalumo_search_integration_id', [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ]);

        register_setting('datalumo_search_settings', 'datalumo_search_post_types', [
            'type'              => 'array',
            'sanitize_callback' => function ($value) {
                if (! is_array($value)) {
                    return [];
                }

                return array_map('sanitize_text_field', $value);
            },
            'default'           => [],
        ]);

        register_setting('datalumo_search_settings', 'datalumo_search_summary_enabled', [
            'type'              => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default'           => false,
        ]);

        register_setting('datalumo_search_settings', 'datalumo_search_summary_selector', [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ]);

        register_setting('datalumo_search_settings', 'datalumo_search_summary_position', [
            'type'              => 'string',
            'sanitize_callback' => [$this, 'sanitizeSummaryPosition'],
            'default'           => 'prepend',
        ]);
    }

    public function sanitizeContentSyncs(mixed $value): array
    {
        if (! is_array($value)) {
            return [];
        }

        $validTypes = array_keys(get_post_types(['public' => true]));
        $syncs = [];

        foreach ($value as $sync) {
            if (! is_array($sync) || empty($sync['id']) || empty($sync['collection_id'])) {
                continue;
            }

            $postTypes = isset($sync['post_types']) && is_array($sync['post_types'])
                ? array_values(array_intersect($sync['post_types'], $validTypes))
                : [];

            $metaMappings = [];

            if (isset($sync['meta_mappings']) && is_array($sync['meta_mappings'])) {
                foreach ($sync['meta_mappings'] as $mapping) {
                    if (! is_array($mapping) || empty($mapping['name']) || empty($mapping['source'])) {
                        continue;
                    }

                    $type = $mapping['type'] ?? '';

                    if (! in_array($type, ['post_meta', 'taxonomy'], true)) {
                        continue;
                    }

                    $metaMappings[] = [
                        'name'       => sanitize_key($mapping['name']),
                        'type'       => $type,
                        'source'     => sanitize_text_field($mapping['source']),
                        'searchable' => ! empty($mapping['searchable']),
                    ];
                }
            }

            $syncs[] = [
                'id'             => sanitize_text_field($sync['id']),
                'collection_id'  => sanitize_text_field($sync['collection_id']),
                'post_types'     => $postTypes,
                'meta_mappings'  => $metaMappings,
            ];
        }

        return $syncs;
    }

    public function sanitizeSummaryPosition(mixed $value): string
    {
        return in_array($value, ['prepend', 'append'], true) ? $value : 'prepend';
    }

    public function sanitizeChatbotMode(mixed $value): string
    {
        return in_array($value, ['popup', 'sidebar'], true) ? $value : 'popup';
    }

    public function sanitizeChatbotPopupPosition(mixed $value): string
    {
        return in_array($value, ['bottom-right', 'bottom-left'], true) ? $value : 'bottom-right';
    }

    public function sanitizeChatbotSidebarSide(mixed $value): string
    {
        return in_array($value, ['right', 'left'], true) ? $value : 'right';
    }

    private static array $tabSlugs = ['api-connection', 'content-sync', 'chatbot', 'search-box', 'enhanced-search'];

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

        wp_enqueue_style('datalumo-admin', plugins_url('resources/css/admin-settings.css', DATALUMO_FILE), [], DATALUMO_VERSION);
        wp_enqueue_script('datalumo-admin', plugins_url('resources/js/admin-settings.js', DATALUMO_FILE), ['jquery'], DATALUMO_VERSION, true);

        $currentTab = $this->resolveCurrentTab();

        wp_localize_script('datalumo-admin', 'datalumoAdmin', [
            'ajaxUrl'     => admin_url('admin-ajax.php'),
            'nonce'       => wp_create_nonce('datalumo_admin'),
            'siteDomain'  => wp_parse_url(home_url(), PHP_URL_HOST),
            'apiKeyValid' => datalumo_is_configured(),
            'currentTab'  => $currentTab,
            'taxonomies'  => array_values(array_map(function ($tax) {
                return ['name' => $tax->name, 'label' => $tax->label];
            }, get_taxonomies(['public' => true], 'objects'))),
            'i18n'        => [
                'testing'           => __('Testing...', 'datalumo'),
                'testSuccess'       => __('Connection successful! API key saved.', 'datalumo'),
                'testFailed'        => __('Connection failed: ', 'datalumo'),
                'saving'            => __('Saving...', 'datalumo'),
                'syncing'           => __('Syncing...', 'datalumo'),
                'syncStarted'       => __('Bulk sync started.', 'datalumo'),
                'syncFailed'        => __('Failed to start sync: ', 'datalumo'),
                'syncComplete'      => __('Sync complete!', 'datalumo'),
                'syncProgress'      => __('Syncing: {processed} / {total} entries', 'datalumo'),
                'syncAlreadyActive' => __('A sync is already in progress.', 'datalumo'),
                'syncCancel'        => __('Cancel', 'datalumo'),
                'syncCancelling'    => __('Cancelling...', 'datalumo'),
                'syncCancelled'     => __('Sync cancelled.', 'datalumo'),
                'syncCancelConfirm' => __('Cancel this sync? Any currently running batch will still finish, but no further batches will run.', 'datalumo'),
                'syncSaveFirst'     => __('Please save your changes before syncing.', 'datalumo'),
                'loading'           => __('Loading...', 'datalumo'),
                'creating'          => __('Creating...', 'datalumo'),
                'createCollection'  => __('+ Create new collection', 'datalumo'),
                'collectionName'    => __('Enter collection name:', 'datalumo'),
                'createIntegration'       => __('+ Create new', 'datalumo'),
                'createIntegrationSubmit' => __('Create Integration', 'datalumo'),
                'integrationName'         => __('Enter integration name:', 'datalumo'),
                'selectCollection'        => __('Please select at least one collection.', 'datalumo'),
                'noItems'                 => __('No items found.', 'datalumo'),
                'addContentSync'          => __('+ Add Content Sync', 'datalumo'),
                'deleteContentSync'       => __('Delete', 'datalumo'),
                'confirmDeleteSync'       => __('Are you sure you want to delete this content sync? Entries will be removed from Datalumo.', 'datalumo'),
                'deletingSyncEntries'     => __('Deleting entries...', 'datalumo'),
                'newSync'                 => __('New sync', 'datalumo'),
                'selectCollectionPlaceholder' => __('-- Select a collection --', 'datalumo'),
                'metaName'                => __('Name', 'datalumo'),
                'metaSource'              => __('Source key', 'datalumo'),
                'metaSearchable'          => __('Searchable', 'datalumo'),
                'metaTypeCustomField'     => __('Custom field', 'datalumo'),
                'metaTypeTaxonomy'        => __('Taxonomy', 'datalumo'),
                'metaSelectTaxonomy'      => __('-- Select taxonomy --', 'datalumo'),
            ],
        ]);
    }

    public function renderPage(): void
    {
        if (! current_user_can('manage_options')) {
            return;
        }

        $currentTab = $this->resolveCurrentTab();

        include DATALUMO_DIR . '/resources/views/settings.php';
    }

    private function resolveCurrentTab(): string
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $tab = isset($_GET['tab']) && in_array($_GET['tab'], self::$tabSlugs, true)
            ? sanitize_text_field($_GET['tab'])
            : 'api-connection';

        if (! datalumo_is_configured()) {
            $tab = 'api-connection';
        }

        return $tab;
    }
}
