<?php

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

class ButlerChat extends \GriffinForms\Admin\App\Html\Widgets\Format
{
    public function getHtml()
    {
        $surface = 'form_builder';
        $prompt_registry = new \GriffinForms\Includes\Ai\PromptRegistry\PromptRegistry();
        $surface_registry = new \GriffinForms\Includes\Ai\AssistSurfaceRegistry();
        $surface_config = $surface_registry->get($surface) ?? [];
        $can_render = $surface_registry->canRender($surface, $prompt_registry);
        $prompt = $this->getInitialPrompt();
        $form_id = isset($_GET['form_id']) ? absint($_GET['form_id']) : 0;
        $provider_meta = $this->getActiveProviderMeta();
        $provider_icon = (string) ($provider_meta['icon'] ?? '');
        $provider_name = (string) ($provider_meta['title'] ?? __('AI', 'griffinforms-form-builder'));
        $assist_icon = trailingslashit($this->config->getRootUrl()) . 'admin/images/butler/icons/griffin-assist.png';
        $current_user = wp_get_current_user();
        $user_avatar = $current_user instanceof \WP_User
            ? get_avatar_url($current_user->ID, ['size' => 32, 'default' => 'mystery'])
            : '';
        $user_name = $current_user instanceof \WP_User
            ? (string) $current_user->display_name
            : '';
        $presentation_mode = sanitize_key((string) ($surface_config['presentation_mode'] ?? 'docked_sidebar'));
        $chat_mode_toggle = !empty($surface_config['chat_mode_toggle']);
        $default_chat_mode = !empty($surface_config['default_chat_mode']);
        $show_suggestions = !empty($surface_config['show_suggestions']);
        $theme_variant = sanitize_key((string) (($surface_config['overrides']['theme_variant'] ?? 'builder')));
        $site_language = sanitize_text_field((string) get_bloginfo('language'));
        $ai_availability = new \GriffinForms\Includes\Ai\AiAvailabilityState();
        $assist_key_configured = $ai_availability->isActive();
        $assist_provider_mapped = $ai_availability->isProviderMapped();
        $connector_providers = $ai_availability->getAvailableConnectorProviders();
        $settings = \GriffinForms\Settings::getInstance();
        $active_provider = sanitize_key((string) $settings->getOption('butler_active_provider', ''));
        $requires_consent = $active_provider !== '' && $active_provider !== 'mock';
        $consent_acknowledged = (int) $settings->getOption('ai_data_sharing_acknowledged', 0) === 1;
        $settings_url = admin_url('admin.php?page=griffinforms-settings-ai');
        $package_state_resolver = \GriffinForms\Includes\Packages\PackageStateResolver::getInstance();
        $package_context = (array) ($package_state_resolver->getState() ?? []);
        $should_auto_start = $assist_key_configured && $this->shouldAutoStart();
        
        echo '<div id="' . esc_attr($this->getHtmlId()) . '" 
                   class="gf-butler-chat-container d-flex flex-column h-100" 
                   data-gf-surface="' . esc_attr($surface) . '"
                   data-gf-presentation-mode="' . esc_attr($presentation_mode) . '"
                   data-gf-theme-variant="' . esc_attr($theme_variant) . '"
                   data-gf-default-chat-mode="' . esc_attr($default_chat_mode ? '1' : '0') . '"
                   data-gf-chat-mode-toggle="' . esc_attr($chat_mode_toggle ? '1' : '0') . '"
                   data-gf-provider-icon="' . esc_url($provider_icon) . '"
                   data-gf-provider-name="' . esc_attr($provider_name) . '"
                   data-gf-assist-icon="' . esc_url($assist_icon) . '"
                   data-gf-user-avatar="' . esc_url($user_avatar) . '"
                   data-gf-user-name="' . esc_attr($user_name) . '"
                   data-gf-site-language="' . esc_attr($site_language) . '"
                   data-gf-assist-key-configured="' . esc_attr($assist_key_configured ? '1' : '0') . '"
                   data-gf-settings-url="' . esc_url($settings_url) . '"
                   data-gf-package-context="' . esc_attr(wp_json_encode($package_context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)) . '"
                   data-gf-nonce="' . esc_attr(wp_create_nonce('initialize_ai_draft')) . '"
                   data-gf-undo-nonce="' . esc_attr(wp_create_nonce('undo_ai_draft')) . '"
                   data-gf-reset-nonce="' . esc_attr(wp_create_nonce('reset_ai_draft')) . '"
                   data-gf-translate-nonce="' . esc_attr(wp_create_nonce('translate_ai_draft')) . '"
                   data-gf-form-id="' . esc_attr($form_id) . '"
                   data-gf-initial-prompt="' . esc_attr($prompt) . '"
                   data-gf-auto-start="' . esc_attr($should_auto_start ? '1' : '0') . '">';

        if (!$can_render) {
            echo '<div class="gf-butler-surface-unavailable p-3 small text-muted">';
            echo esc_html__('Griffin Assist is not available on this page yet because the required context contract is not registered.', 'griffinforms-form-builder');
            echo '</div>';
            echo '</div>';
            return;
        }

        if (!$assist_provider_mapped) {
            $activate_nonce = wp_create_nonce('griffinforms_activate_provider');
            $provider_labels = [
                'openai'    => 'OpenAI',
                'anthropic' => 'Anthropic',
                'gemini'    => 'Google Gemini',
            ];
            echo '<div class="gf-butler-setup-notice m-3 p-3 border rounded bg-light">';
            echo '<div class="fw-semibold mb-1">' . esc_html__('Griffin Assist needs an AI provider selected', 'griffinforms-form-builder') . '</div>';
            if (!empty($connector_providers)) {
                echo '<div class="small text-muted mb-2">' . esc_html__('AI providers are already configured in WordPress. Select one to activate:', 'griffinforms-form-builder') . '</div>';
                echo '<div class="d-flex flex-wrap gap-2 mb-2">';
                foreach ($connector_providers as $provider_id) {
                    $label = $provider_labels[$provider_id] ?? $provider_id;
                    echo '<button type="button"'
                        . ' class="button gf-butler-activate-connector-btn"'
                        . ' data-provider="' . esc_attr($provider_id) . '"'
                        . ' data-nonce="' . esc_attr($activate_nonce) . '">'
                        . esc_html($label)
                        . '</button>';
                }
                echo '</div>';
                echo '<div class="small text-muted">';
                echo esc_html__('Or configure manually:', 'griffinforms-form-builder') . ' ';
                echo '<a href="' . esc_url($settings_url) . '" class="gf-butler-setup-state__link">' . esc_html__('Open Griffin Assist settings', 'griffinforms-form-builder') . '</a>';
                echo '</div>';
            } else {
                echo '<div class="small text-muted">';
                echo esc_html__('Choose and save an AI provider in Settings before using Griffin Assist entry points.', 'griffinforms-form-builder') . ' ';
                echo '<a href="' . esc_url($settings_url) . '" class="gf-butler-setup-state__link">' . esc_html__('Open Griffin Assist settings', 'griffinforms-form-builder') . '</a>';
                echo '</div>';
            }
            echo '</div>';
        } elseif (!$assist_key_configured) {
            $help_url = 'https://griffinforms.com/docs/user-docs/griffin-assist/get-your-api-key.php';
            echo '<div class="gf-butler-setup-notice m-3 p-3 border rounded bg-light">';
            echo '<div class="fw-semibold mb-1">' . esc_html__('Griffin Assist needs an API key', 'griffinforms-form-builder') . '</div>';
            echo '<div class="small text-muted">';
            echo esc_html__('An AI provider is selected, but its API key has not been saved yet.', 'griffinforms-form-builder') . ' ';
            echo '<a href="' . esc_url($help_url) . '" target="_blank" rel="noopener noreferrer" class="gf-butler-setup-state__link">' . esc_html__('How to get your API key', 'griffinforms-form-builder') . '</a>';
            echo ' &middot; ';
            echo '<a href="' . esc_url($settings_url) . '" class="gf-butler-setup-state__link">' . esc_html__('Open settings', 'griffinforms-form-builder') . '</a>';
            echo '</div>';
            echo '</div>';
        }
        
        // Butler Header
        echo '<div class="gf-butler-header d-flex align-items-center p-3 border-bottom">';
        echo '<div>';
        echo '<div class="gf-butler-title-row d-flex align-items-center gap-2">';
        echo '<h6 class="mb-0 gf-butler-title d-flex align-items-center gap-2">';
        echo '<span>' . esc_html__('Griffin Assist', 'griffinforms-form-builder') . '</span>';
        echo '</h6>';
        if ($provider_icon !== '') {
            echo '<span class="gf-butler-provider-chip" title="' . esc_attr($provider_name) . '">';
            echo '<img src="' . esc_url($provider_icon) . '" alt="' . esc_attr($provider_name) . '" width="14" height="14">';
            echo '<span>' . esc_html($provider_name) . '</span>';
            echo '</span>';
        }
        echo '</div>';
        echo '<div class="gf-butler-status-row d-flex align-items-center justify-content-between gap-2">';
        echo '<div class="gf-butler-status small text-muted">' . esc_html__('Ready to assist with your form', 'griffinforms-form-builder') . '</div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';

        // Chat Log
        echo '<div id="gf-butler-chat-log" class="gf-butler-chat-log flex-grow-1 overflow-y-auto p-3 bg-light">';
        if (!$assist_key_configured) {
            $this->renderGreeting();
        } elseif ($should_auto_start && $prompt !== '') {
            $this->renderMessage('user', $prompt);
            $this->renderIntermediaryAlert('Analysing your request...');
        } else {
            // A stored initial prompt does not imply a live pending request.
            // Only render the pending bootstrap UI on the one autostart load.
            $this->renderGreeting();
        }
        echo '<div id="butler-chat-bottom"></div>';
        echo '</div>';

        // Floating "New message" pill (hidden by default)
        echo '<button type="button" id="gf-butler-new-message-pill" class="gf-butler-new-message-pill btn btn-sm btn-primary rounded-pill" style="display:none;">';
        echo esc_html__('↓ New message', 'griffinforms-form-builder');
        echo '</button>';

        // Prompt Chips / Suggestions
        if ($show_suggestions) {
            echo '<div class="gf-butler-suggestions p-2 bg-white">';
            $this->renderPromptChips();
            echo '</div>';
        }

        // Input Area
        echo '<div class="gf-butler-input-area p-3 bg-white">';
        echo '<div class="gf-butler-composer">';
        echo '<textarea id="gf-butler-chat-input" class="gf-butler-composer__textarea form-control" placeholder="' . esc_attr__('Ask a question or describe a change...', 'griffinforms-form-builder') . '" rows="2"' . ($assist_key_configured ? '' : ' disabled="disabled"') . '></textarea>';
        echo '<div class="gf-butler-composer__divider"></div>';
        echo '<div class="gf-butler-composer__toolbar d-flex align-items-center justify-content-between gap-2">';
        echo '<div class="d-flex align-items-center gap-1">';
        echo '<button type="button" class="btn gf-butler-action-btn gf-butler-action-btn--undo" id="gf-butler-undo-btn" title="' . esc_attr__('Undo Last Action', 'griffinforms-form-builder') . '" aria-label="' . esc_attr__('Undo Last Action', 'griffinforms-form-builder') . '"' . ($assist_key_configured ? '' : ' disabled="disabled"') . '>';
        echo esc_html__('Undo', 'griffinforms-form-builder');
        echo '</button>';
        echo '<button type="button" class="btn gf-butler-action-btn gf-butler-action-btn--reset" id="gf-butler-reset-btn" title="' . esc_attr__('Reset to Start', 'griffinforms-form-builder') . '" aria-label="' . esc_attr__('Reset to Start', 'griffinforms-form-builder') . '"' . ($assist_key_configured ? '' : ' disabled="disabled"') . '>';
        echo esc_html__('Reset', 'griffinforms-form-builder');
        echo '</button>';
        if ($chat_mode_toggle) {
            echo '<button type="button" class="gf-butler-chatmode-toggle" id="gf-butler-chatmode-toggle" aria-pressed="' . esc_attr($default_chat_mode ? 'true' : 'false') . '" title="' . esc_attr__('Toggle Chat Mode', 'griffinforms-form-builder') . '"' . ($assist_key_configured ? '' : ' disabled="disabled"') . '>';
            echo '<span class="gf-butler-chatmode-toggle__dot" aria-hidden="true"></span>';
            echo '<span class="gf-butler-chatmode-toggle__label">' . esc_html__('Chat', 'griffinforms-form-builder') . '</span>';
            echo '</button>';
        }
        echo '</div>';
        echo '<button class="btn btn-primary gf-butler-send-btn" type="button" id="gf-butler-send-btn"' . ($assist_key_configured ? '' : ' disabled="disabled"') . '>';
        echo '<img class="gf-butler-send-btn__icon" src="' . esc_url(trailingslashit($this->config->getRootUrl()) . 'admin/images/butler/icons/send.svg') . '" alt="" width="16" height="16">';
        echo '</button>';
        echo '</div>';
        echo '</div>';
        if ($assist_key_configured && $requires_consent && !$consent_acknowledged) {
            echo '<div class="gf-butler-disclosure small text-muted mt-2">';
            echo esc_html__('Using AI may send relevant form data to your configured provider.', 'griffinforms-form-builder') . ' ';
            echo '<a href="' . esc_url($settings_url) . '">' . esc_html__('Review AI settings', 'griffinforms-form-builder') . '</a>';
            echo '</div>';
        }
        echo '</div>';

        echo '</div>';
    }

    private function getInitialPrompt(): string
    {
        $form_id = isset($_GET['form_id']) ? absint($_GET['form_id']) : 0;
        if (!$form_id) {
            return '';
        }

        $integration_settings = $this->sql->getItemValue($form_id, 'integration_settings', 'form');
        $settings = $this->maybeDecode($integration_settings);
        
        return (string) ($settings['ai_draft']['prompt'] ?? '');
    }

    private function shouldAutoStart(): bool
    {
        $form_id = isset($_GET['form_id']) ? absint($_GET['form_id']) : 0;
        if (!$form_id) {
            return false;
        }

        $integration_settings = $this->sql->getItemValue($form_id, 'integration_settings', 'form');
        $settings = $this->maybeDecode($integration_settings);

        if (empty($settings['ai_draft']['auto_start_pending'])) {
            return false;
        }

        // Consume the flag immediately so reopening the builder never re-fires the prompt.
        $settings['ai_draft']['auto_start_pending'] = 0;
        global $wpdb;
        $wpdb->update(
            $this->config->getTable('form'),
            ['integration_settings' => maybe_serialize($settings)],
            ['id' => $form_id],
            ['%s'],
            ['%d']
        );

        return true;
    }

    private function renderGreeting()
    {
        $this->renderMessage('assistant', __('Hello! I am your Griffin Assist. I can help you build and refine your form. What would you like to do?', 'griffinforms-form-builder'));
    }

    private function renderMessage(string $role, string $message)
    {
        $class = $role === 'user' ? 'gf-butler-msg-user align-self-end' : 'gf-butler-msg-assistant align-self-start';
        $provider_meta = $this->getActiveProviderMeta();
        $provider_icon = (string) ($provider_meta['icon'] ?? '');
        $avatar = '';
        if ($role === 'assistant') {
            $avatar = '<div class="gf-butler-msg-avatar me-2">' . $this->renderAssistMark($provider_icon, 'xs') . '</div>';
        } elseif ($role === 'user') {
            $avatar = '<div class="gf-butler-msg-avatar">' . $this->renderUserAvatar() . '</div>';
        }

        echo '<div class="gf-butler-msg d-flex mb-3 ' . esc_attr($class) . '">';
        echo $avatar;
        echo '<div class="gf-butler-msg-bubble p-2 rounded">';
        echo wp_kses_post($message);
        echo '</div>';
        echo '</div>';
    }

    private function renderIntermediaryAlert(string $message)
    {
        echo '<div class="gf-butler-msg gf-butler-msg-system d-flex mb-3 align-self-start">';
        echo '<div class="gf-butler-msg-bubble p-2 rounded bg-white small text-muted d-flex">';
        echo '<span class="gf-butler-loader me-2" aria-hidden="true"></span>';
        echo esc_html($message);
        echo '</div>';
        echo '</div>';
    }

    private function renderPromptChips()
    {
        $chips = [
            __('Add email field', 'griffinforms-form-builder'),
            __('Add phone field', 'griffinforms-form-builder'),
            __('Add message field', 'griffinforms-form-builder'),
            __('Add file upload field', 'griffinforms-form-builder')
        ];

        echo '<div class="d-flex flex-wrap gap-1">';
        foreach ($chips as $chip) {
            echo '<button type="button" class="btn btn-outline-secondary btn-sm gf-butler-prompt-chip">' . esc_html($chip) . '</button>';
        }
        echo '</div>';
    }

    public function getJs()
    {
        // JS will be handled in a dedicated file, but we can output inline initialization if needed.
    }

    private function getActiveProviderMeta(): array
    {
        $provider = '';

        try {
            $router = new \GriffinForms\Includes\Ai\ButlerModelRouter();
            $route = $router->route('form_drafting');
            $provider = sanitize_key((string) ($route['provider'] ?? ''));
        } catch (\Throwable $throwable) {
            $provider = '';
        }

        if ($provider === '') {
            return [];
        }

        try {
            $providers = \GriffinForms\Includes\Integrations\Providers::getInstance();
            $meta = $providers->get($provider, false);
            return is_array($meta) ? $meta : [];
        } catch (\Throwable $throwable) {
            return [];
        }
    }

    private function renderAssistMark(string $provider_icon = '', string $size = 'sm'): string
    {
        $label = esc_html__('Griffin Assist', 'griffinforms-form-builder');
        $size_class = $size === 'xs' ? 'gf-butler-mark--xs' : 'gf-butler-mark--sm';
        $assist_icon = trailingslashit($this->config->getRootUrl()) . 'admin/images/butler/icons/griffin-assist.png';
        $html = '<span class="gf-butler-mark ' . esc_attr($size_class) . '" aria-label="' . esc_attr($label) . '"><img class="gf-butler-mark__icon" src="' . esc_url($assist_icon) . '" alt="" width="16" height="16">';
        if ($provider_icon !== '') {
            $html .= '<span class="gf-butler-mark__provider-badge"><img src="' . esc_url($provider_icon) . '" alt="" width="10" height="10"></span>';
        }
        $html .= '</span>';

        return $html;
    }

    private function renderUserAvatar(): string
    {
        $current_user = wp_get_current_user();
        $display_name = $current_user instanceof \WP_User ? (string) $current_user->display_name : __('User', 'griffinforms-form-builder');
        $avatar_url = $current_user instanceof \WP_User
            ? get_avatar_url($current_user->ID, ['size' => 32, 'default' => 'mystery'])
            : '';

        if ($avatar_url !== '') {
            return '<img class="gf-butler-user-avatar" src="' . esc_url($avatar_url) . '" alt="' . esc_attr($display_name) . '" width="24" height="24">';
        }

        $initial = strtoupper(function_exists('mb_substr') ? mb_substr($display_name, 0, 1) : substr($display_name, 0, 1));
        return '<span class="gf-butler-user-avatar gf-butler-user-avatar--fallback" aria-label="' . esc_attr($display_name) . '">' . esc_html($initial) . '</span>';
    }
}
