<?php

namespace Kanews\Kai\Admin;

use Kanews\Kai\Manager;
use Kanews\Kai\Support\Options;

class AdminUi
{
    private $manager;

    public function __construct(Manager $manager)
    {
        $this->manager = $manager;
    }

    public function register(): void
    {
        add_action('add_meta_boxes', [$this, 'addMetaBox']);
        add_action('admin_footer', [$this, 'renderPopupContent']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueScripts']);
        add_action('admin_post_kanews_save_kai_settings', [$this, 'handleSaveSettings']);
        add_action('wp_ajax_kanews_test_ai_provider', [$this, 'ajaxTestProvider']);
    }

    public function addMetaBox(): void
    {
        add_meta_box(
            'kanews_ai_meta_box',
            'Kanews AI <span class="kanews-ai-badge" style="font-size: 11px; font-weight: 500; padding: 4px 10px; border-radius: 3px; margin-left: 5px; color: #10AC84; background: rgba(16,172,132,0.1);">KAI</span>',
            [$this, 'renderMetaBox'],
            ['post', 'columist'],
            'side',
            'high'
        );
    }

    public function renderMetaBox(): void
    {
        echo '<div class="kanews-ai-metabox-trigger"><br>
            <div class="components-flex components-h-stack components-v-stack css-8mn8b1 e19lxcc00">
                <div id="kanews-ai-launch" class="components-button button editor-post-trash is-next-40px-default-size is-secondary" style="display:flex;align-items:center"><svg width="24" height="24" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M3 19V5.70046C3 5.27995 3.26307 4.90437 3.65826 4.76067L13.3291 1.24398C13.5886 1.14961 13.8755 1.28349 13.9699 1.54301C13.9898 1.59778 14 1.65561 14 1.71388V6.6667L20.3162 8.77211C20.7246 8.90822 21 9.29036 21 9.72079V19H23V21H1V19H3ZM5 19H12V3.85543L5 6.40089V19ZM19 19V10.4416L14 8.77488V19H19Z"></path></svg> KAI\'yi Başlat</div>
            </div></div>';
        wp_nonce_field('kanews_ai_nonce_action', 'kanews_ai_nonce_name');
    }

    public function renderPopupContent(): void
    {
        $screen = get_current_screen();
        if (!in_array($screen->base, ['post', 'post-new'], true)) {
            return;
        }

        $openaiStatus = !empty(Options::getApiKey('openai'));
        $geminiStatus = !empty(Options::getApiKey('gemini'));
        ?>
        <div id="kanews-ai-popup" class="kanews-ai-popup" style="display:none">
            <div class="kanews-ai-popup-content">
                <div class="kanews-ai-popup-header">
                    <h2>Kanews AI <span class="kanews-ai-badge">KAI</span></h2>
                    <span class="kanews-ai-popup-close">&times;</span>
                </div>

                <div class="kanews-ai-popup-body">
                    <div class="kanews-ai-task-selector">
                        <select id="kanews-ai-selector" class="components-button editor-post-trash is-next-40px-default-size is-secondary">
                            <option value="">Görev Seç</option>
                            <option value="article">Makale Oluştur</option>
                            <option value="paraphrase">Makale Özgünleştirici</option>
                            <option value="translate">Makale Çevirici</option>
                            <option value="featured-image">Öne Çıkarılan Görsel</option>
                            <option value="tts">Ses Dosyası Oluştur</option>
                            <option value="excerpt">Yazı Açıklaması</option>
                            <option value="summary">Yazı Özeti</option>
                            <option value="seo-title">SEO Başlığı</option>
                            <option value="comments">Yorum Oluştur</option>
                            <option value="faq">SSS Oluştur</option>
                        </select>
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24"><path d="M11.9999 13.1714L16.9497 8.22168L18.3639 9.63589L11.9999 15.9999L5.63599 9.63589L7.0502 8.22168L11.9999 13.1714Z"></path></svg>
                    </div>

                    <div class="kanews-ai-provider-selector">
                        <label for="kanews-ai-provider"><?php esc_html_e('Model Seçimi', 'kanews'); ?></label>
                        <select id="kanews-ai-provider" class="components-button editor-post-trash is-next-40px-default-size is-secondary">
                            <?php foreach ($this->manager->ai()->availableProviders() as $provider): ?>
                                <option value="<?php echo esc_attr($provider); ?>" <?php selected($provider, Options::getDefaultProvider()); ?>>
                                    <?php echo esc_html(ucfirst($provider)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div id="kanews-ai-task-inputs"></div>
                    <div id="kanews-ai-results" class="kanews-ai-results"></div>
                </div>

                <div class="kanews-ai-popup-footer">
                    <div class="kanews-ai-api-status">
                        <div class="api-status-item">
                            <span class="label">OpenAI API:</span>
                            <span class="status <?php echo $openaiStatus ? 'active' : 'inactive'; ?>">
                                <?php echo $openaiStatus ? 'Aktif' : 'Pasif'; ?>
                            </span>
                        </div>
                        <div class="api-status-item">
                            <span class="label">Gemini API:</span>
                            <span class="status <?php echo $geminiStatus ? 'active' : 'inactive'; ?>">
                                <?php echo $geminiStatus ? 'Aktif' : 'Pasif'; ?>
                            </span>
                        </div>
                        <div class="api-status-item">
                            <span class="label">KAI v3.0</span>
                        </div>
                    </div>
                    <div style="display: flex; align-items: center; justify-content: space-between;gap:10px">
                        <div id="kanews-ai-loading"></div>
                        <button id="kanews-ai-execute" class="components-button is-primary button" disabled>Görevi Başlat</button>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    public function enqueueScripts(string $hook): void
    {
        if (!in_array($hook, ['post.php', 'post-new.php'], true)) {
            return;
        }

        wp_enqueue_style('kanews-ai-admin-style', KAN_TEMPLATE_URL . '/assets/css/admin.css', [], null);

        $dependencies = ['jquery'];
        if (function_exists('wp_enqueue_block_editor_assets')) {
            $dependencies = array_merge($dependencies, [
                'wp-plugins',
                'wp-edit-post',
                'wp-element',
                'wp-components',
                'wp-data',
            ]);
        }

        wp_enqueue_script(
            'kanews-ai-script',
            KAN_TEMPLATE_URL . '/assets/js/admin/kanews-ai.js',
            $dependencies,
            null,
            true
        );

        wp_localize_script(
            'kanews-ai-script',
            'kanewsAiConfig',
            [
                'apiStatus' => [
                    'openai' => !empty(Options::getApiKey('openai')),
                    'gemini' => !empty(Options::getApiKey('gemini')),
                ],
            ]
        );
    }

    public function handleSaveSettings(): void
    {
        if (!current_user_can('manage_options')) {
            wp_die(__('Bu işlem için yetkiniz yok.', 'kanews'));
        }
        check_admin_referer('kanews_save_kai_settings');

        // Read dedicated KAI options to avoid being wiped by other admin saves.
        $opts = get_option('kanews_kai_options', []);
        if (!is_array($opts)) {
            $opts = [];
        }

        $isAudioPanel = !empty($_POST['kai_audio_panel']);

        // Cron interval update via feed state
        if (isset($_POST['kai_cron_interval'])) {
            $interval = sanitize_text_field(wp_unslash($_POST['kai_cron_interval']));
            $validIntervals = ['quarterhourly', 'half-hourly', 'hourly', 'twicedaily', 'daily'];
            if (in_array($interval, $validIntervals, true)) {
                $state = $this->manager->feeds()->getState();
                $state['settings']['interval'] = $interval;
                $this->manager->feeds()->saveState($state);
            }
        }

        $opts['openai-api'] = isset($_POST['openai_api']) ? sanitize_text_field(wp_unslash($_POST['openai_api'])) : '';
        $opts['pexels-api'] = isset($_POST['pexels_api']) ? sanitize_text_field(wp_unslash($_POST['pexels_api'])) : '';
        $opts['gemini-api'] = isset($_POST['gemini_api']) ? sanitize_text_field(wp_unslash($_POST['gemini_api'])) : '';
        $opts['kai-chat-active'] = !empty($_POST['kai_chat_active']);
        $opts['kai-chat-title'] = isset($_POST['kai_chat_title']) ? sanitize_text_field(wp_unslash($_POST['kai_chat_title'])) : 'KAI ile Haber Hakkında Sohbet';
        $opts['kai-chat-placeholder'] = isset($_POST['kai_chat_placeholder']) ? sanitize_text_field(wp_unslash($_POST['kai_chat_placeholder'])) : 'Sorunuzu yazın...';
        $opts['kai-chat-free-limit'] = isset($_POST['kai_chat_free_limit']) ? intval($_POST['kai_chat_free_limit']) : 5;
        $opts['kai-chat-premium-limit'] = isset($_POST['kai_chat_premium_limit']) ? intval($_POST['kai_chat_premium_limit']) : 20;
        $opts['kai-chat-text-welcome-free'] = isset($_POST['kai_chat_text_welcome_free']) ? wp_kses_post(wp_unslash($_POST['kai_chat_text_welcome_free'])) : 'Hoş geldiniz, günlük {free_limit} yazı için {free_limit}\'er soru sorabilirsiniz.';
        $opts['kai-chat-text-welcome-premium'] = isset($_POST['kai_chat_text_welcome_premium']) ? wp_kses_post(wp_unslash($_POST['kai_chat_text_welcome_premium'])) : 'Hoş geldiniz, Premium üye olarak günlük {premium_limit} yazı için {premium_limit}\'er soru sorabilirsiniz.';
        $opts['kai-chat-text-remaining-free'] = isset($_POST['kai_chat_text_remaining_free']) ? wp_kses_post(wp_unslash($_POST['kai_chat_text_remaining_free'])) : 'Ücretsiz kullanıcı olarak {remaining} soru hakkınız kaldı.';
        $opts['kai-chat-text-remaining-premium'] = isset($_POST['kai_chat_text_remaining_premium']) ? wp_kses_post(wp_unslash($_POST['kai_chat_text_remaining_premium'])) : 'Premium üye olarak {remaining} soru hakkınız kaldı.';
        $opts['kai-chat-text-upgrade'] = isset($_POST['kai_chat_text_upgrade']) ? wp_kses_post(wp_unslash($_POST['kai_chat_text_upgrade'])) : 'Daha fazlası için <a href="{upgrade_url}">üyelik seçeneklerimizi</a> inceleyin.';

        // Audio settings: update only when audio panel submits to avoid overwriting chat/KAI saves.
        if ($isAudioPanel) {
            $opts['kai-audio-enabled'] = !empty($_POST['kai_audio_enabled']);
            $opts['kai-audio-paused'] = !empty($_POST['kai_audio_paused']);

            if (isset($_POST['kai_audio_voice'])) {
                $voice = sanitize_text_field(wp_unslash($_POST['kai_audio_voice']));
                $allowedVoices = ['alloy', 'verse', 'coral', 'sol'];
                if (in_array($voice, $allowedVoices, true)) {
                    $opts['kai-audio-voice'] = $voice;
                }
            }

            if (isset($_POST['kai_audio_daily_count'])) {
                $count = max(1, min(3, intval($_POST['kai_audio_daily_count'])));
                $opts['kai-audio-daily-count'] = $count;
            }

            $opts['kai-audio-hero-eyebrow'] = isset($_POST['kai_audio_hero_eyebrow']) ? sanitize_text_field(wp_unslash($_POST['kai_audio_hero_eyebrow'])) : get_bloginfo('name');
            $opts['kai-audio-hero-title'] = isset($_POST['kai_audio_hero_title']) ? sanitize_text_field(wp_unslash($_POST['kai_audio_hero_title'])) : __('KAI Haber Bülteni', 'kanews');
            $opts['kai-audio-hero-description'] = isset($_POST['kai_audio_hero_desc']) ? sanitize_textarea_field(wp_unslash($_POST['kai_audio_hero_desc'])) : __('Günün kritik başlıklarını KAI üç farklı zaman diliminde haber bültenine dönüştürür. Kulaklığınızı takın, gündemi dakikalar içinde yakalayın.', 'kanews');
        }

        // Persist only to dedicated KAI option (no kanews_options mirroring).
        update_option('kanews_kai_options', $opts, false);

        // Update audio briefing schedule
        if ($opts['kai-audio-enabled']) {
            $this->manager->audio()->maybeSchedule();
        } else {
            $this->manager->audio()->clearSchedule();
        }

        set_transient('kanews_kai_notice', [
            'type' => 'success',
            'message' => __('KAI ayarları kaydedildi.', 'kanews'),
        ], 45);

        $anchor = !empty($_POST['kai_audio_panel']) ? '#kai-audio' : '#kai-settings';
        wp_safe_redirect(admin_url('admin.php?page=kanews-kai' . $anchor));
        exit;
    }

    public function ajaxTestProvider(): void
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Bu işlem için yetkiniz yok.', 'kanews')], 403);
        }

        $nonce = sanitize_text_field($_POST['nonce'] ?? '');
        if (!wp_verify_nonce($nonce, 'kanews_ai_test_provider')) {
            wp_send_json_error(['message' => __('Geçersiz istek.', 'kanews')], 403);
        }

        $provider = sanitize_text_field($_POST['provider'] ?? '');
        if (!in_array($provider, ['openai', 'gemini'], true)) {
            wp_send_json_error(['message' => __('Bilinmeyen sağlayıcı.', 'kanews')]);
        }

        $apiKey = Options::getApiKey($provider);
        if (empty($apiKey)) {
            wp_send_json_error(['message' => __('Önce geçerli bir API anahtarı kaydedin.', 'kanews')]);
        }

        try {
            $this->pingProvider($provider, $apiKey);
            $label = $provider === 'gemini' ? 'Gemini' : 'OpenAI';
            wp_send_json_success(['message' => sprintf(__('%s bağlantısı başarılı.', 'kanews'), $label)]);
        } catch (\Throwable $th) {
            wp_send_json_error(['message' => $th->getMessage()]);
        }
    }

    private function pingProvider(string $provider, string $apiKey): void
    {
        if ($provider === 'gemini') {
            $endpoint = sprintf(
                'https://generativelanguage.googleapis.com/v1/models?key=%s&pageSize=1',
                rawurlencode($apiKey)
            );
            $response = wp_remote_get($endpoint, ['timeout' => 15]);
        } else {
            $response = wp_remote_get('https://api.openai.com/v1/models?limit=1', [
                'timeout' => 15,
                'headers' => [
                    'Authorization' => 'Bearer ' . $apiKey,
                ],
            ]);
        }

        if (is_wp_error($response)) {
            throw new \RuntimeException($response->get_error_message());
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        if ($code >= 400) {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $message = $body['error']['message'] ?? __('API bağlantısı başarısız oldu.', 'kanews');
            throw new \RuntimeException($message);
        }
    }

    public function renderAdminPage(): void
    {
        $renderer = new AdminPageRenderer($this->manager);
        $renderer->render();
    }
}

