<?php

namespace GriffinForms\Admin\Html\Pages\Settings;

use GriffinForms\Includes\Integrations\Providers;

class Ai extends \GriffinForms\Admin\Html\Pages\Settings\Format
{
    /**
     * AI integration registry.
     *
     * @var \GriffinForms\Includes\Integrations\Providers
     */
    protected $providers;

    public function __construct()
    {
        $this->providers = Providers::getInstance();
        parent::__construct();
        $this->choices = \GriffinForms\Admin\Choices\Ai::getInstance();
    }

    protected function settingsGroupOptions()
    {
        $this->getOptionHtml('butler_active_provider');
        $this->getOptionHtml('butler_generation_timeout');
        $this->getOptionHtml('ai_data_sharing_acknowledged');
    }

    protected function getButlerActiveProviderHtml($input_id)
    {
        $this->option = $this->settings->getOptionHistory('butler_active_provider', '');
        $current_value = sanitize_key((string) ($this->option['current_value'] ?? ''));
        if ($current_value === '') {
            $current_value = sanitize_key((string) $this->settings->getOption('ai_provider', ''));
        }
        $providers = $this->getAiProviderChoices();

        echo '<div class="griffinforms-setting-field">';
        echo '<select id="' . esc_attr($input_id) . '" name="butler_active_provider">';
        echo '<option value="">' . esc_html__('Select a provider', 'griffinforms-form-builder') . '</option>';

        foreach ($providers as $value => $provider) {
            $label = $provider['label'];
            if (!$provider['configured']) {
                $label .= ' — ' . esc_html__('Not configured', 'griffinforms-form-builder');
            }

            echo '<option value="' . esc_attr($value) . '" ' . selected($current_value, $value, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';

        $this->getOptionDescription('butler_active_provider');
        $this->renderProviderStatus($current_value, $providers);
        $this->displayOptionHistory();
        echo '</div>';
    }

    protected function getButlerGenerationTimeoutHtml($input_id)
    {
        $this->option = $this->settings->getOptionHistory('butler_generation_timeout', '20');
        $current_value = (string) ($this->option['current_value'] ?? '20');
        if ($current_value === '' || $current_value === 'none') {
            $current_value = (string) $this->settings->getOption('ai_timeout', '20');
        }
        if (!in_array($current_value, ['10', '20', '30'], true)) {
            $current_value = '20';
        }

        echo '<div class="griffinforms-setting-field">';
        echo '<select id="' . esc_attr($input_id) . '" name="butler_generation_timeout">';
        foreach ($this->getTimeoutChoices() as $value => $label) {
            echo '<option value="' . esc_attr($value) . '" ' . selected($current_value, $value, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';

        $this->getOptionDescription('butler_generation_timeout');
        $this->displayOptionHistory();
        echo '</div>';
    }

    protected function getAiDataSharingAcknowledgedHtml($input_id)
    {
        $this->option = $this->settings->getOptionHistory('ai_data_sharing_acknowledged', 0);
        $current_value = (int) ($this->option['current_value'] ?? 0);
        $ack_timestamp = (string) $this->settings->getOption('ai_data_sharing_acknowledged_at', '');
        $ack_version = (string) $this->settings->getOption('ai_data_sharing_acknowledged_version', '');

        echo '<div class="griffinforms-setting-field">';
        echo '<label for="' . esc_attr($input_id) . '" style="display:flex;align-items:flex-start;gap:8px;">';
        echo '<input type="checkbox" id="' . esc_attr($input_id) . '" name="ai_data_sharing_acknowledged" value="1" ' . checked(1, $current_value, false) . ' />';
        echo '<span>' . esc_html__('I understand that relevant form data may be sent to the configured AI provider when using Griffin Assist.', 'griffinforms-form-builder') . '</span>';
        echo '</label>';

        $this->getOptionDescription('ai_data_sharing_acknowledged');

        if ($ack_timestamp !== '') {
            $formatted = wp_date(get_option('date_format') . ' ' . get_option('time_format'), strtotime($ack_timestamp));
            $version_text = $ack_version !== '' ? sprintf(__('Version: %s.', 'griffinforms-form-builder'), $ack_version) : '';
            echo '<p class="description">' . esc_html(sprintf(
                __('Acknowledged on %1$s. %2$s', 'griffinforms-form-builder'),
                $formatted,
                $version_text
            )) . '</p>';
        }

        $this->displayOptionHistory();
        echo '</div>';
    }

    /**
     * Return registered AI provider choices.
     *
     * @return array<string,array{label:string,configured:bool}>
     */
    protected function getAiProviderChoices(): array
    {
        $choices = [];
        $providers = $this->providers->getAll();

        foreach ($providers as $provider_id => $provider) {
            if (($provider['category'] ?? '') !== 'AI') {
                continue;
            }

            $provider_id = sanitize_key((string) $provider_id);
            if ($provider_id === '') {
                continue;
            }

            $label = (string) ($provider['name'] ?? $provider_id);
            $configured = !empty($provider['configured']);

            if (!$configured) {
                $integration = $this->providers->getIntegration($provider_id);
                if ($integration && method_exists($integration, 'isConfigured')) {
                    $configured = (bool) $integration->isConfigured();
                }
            }

            $choices[$provider_id] = [
                'label'      => $label,
                'configured' => $configured,
            ];
        }

        uasort($choices, static function (array $left, array $right): int {
            return strcasecmp($left['label'], $right['label']);
        });

        return $choices;
    }

    /**
     * Render current-provider status below the dropdown.
     */
    protected function renderProviderStatus(string $current_value, array $providers): void
    {
        if ($current_value === '') {
            echo '<p class="description">' . esc_html__('No active AI provider is selected. Griffin Assist AI entry points will remain visible, but AI workflows will guide users to configuration until a provider is selected and configured.', 'griffinforms-form-builder') . '</p>';
            return;
        }

        if (!isset($providers[$current_value])) {
            echo '<p class="description">' . esc_html__('The previously selected AI provider is not currently available in this installation. Select another provider or review your integrations.', 'griffinforms-form-builder') . '</p>';
            return;
        }

        $integration = $this->providers->getIntegration($current_value);
        $status = $integration && method_exists($integration, 'getStatus')
            ? (array) $integration->getStatus()
            : [];

        $message = (string) ($status['message'] ?? '');
        if ($message === '') {
            $message = !empty($providers[$current_value]['configured'])
                ? __('Configured', 'griffinforms-form-builder')
                : __('Configuration required', 'griffinforms-form-builder');
        }

        echo '<p class="description">' . esc_html(sprintf(
            /* translators: 1: provider name, 2: status message */
            __('Current provider: %1$s. Status: %2$s. Configure credentials from the Integrations modal if needed.', 'griffinforms-form-builder'),
            $providers[$current_value]['label'],
            $message
        )) . '</p>';
    }

    /**
     * Return the fixed timeout options for the AI response timeout field.
     *
     * @return array<string,string>
     */
    protected function getTimeoutChoices(): array
    {
        return [
            '10' => __('Fast (10s)', 'griffinforms-form-builder'),
            '20' => __('Standard (20s)', 'griffinforms-form-builder'),
            '30' => __('Extended (30s)', 'griffinforms-form-builder'),
        ];
    }
}
