<?php

namespace GriffinForms\Includes\CommandPalette\Providers;

use GriffinForms\Config;
use GriffinForms\Includes\CommandPalette\SearchProviderInterface;
use GriffinForms\Includes\CommandPalette\SearchResultItem;

class CreateActionsProvider implements SearchProviderInterface
{
    private Config $config;

    public function __construct()
    {
        $this->config = Config::getInstance();
    }

    public function getProviderId(): string { return 'create_actions'; }
    public function getLabel(): string      { return 'Create'; }
    public function getPriority(): int      { return 12; }
    public function getQuickItems(int $form_id): array { return []; }

    public function query(string $query, int $form_id): array
    {
        if ($query === '') {
            return [];
        }

        $default_form_name = sprintf(__('Form #%d', 'griffinforms-form-builder'), $this->getNextFormNumber());

        $entries = [
            [
                'id'          => 'new_form',
                'label'       => __('New Form', 'griffinforms-form-builder'),
                'description' => __('Create a blank form and open it in the builder', 'griffinforms-form-builder'),
                'icon'        => 'form',
                'keywords'    => ['new form', 'create form', 'blank form', 'add form'],
                'action_type' => 'create_blank_form',
                'action_payload' => [
                    'nonce'        => wp_create_nonce('create_blank_form'),
                    'form_name'    => $default_form_name,
                    'redirect_url' => admin_url('admin.php?page=griffinforms-app&form_id='),
                ],
            ],
            [
                'id'          => 'new_message',
                'label'       => __('New Message', 'griffinforms-form-builder'),
                'description' => __('Create a new email message template', 'griffinforms-form-builder'),
                'icon'        => 'nav_messages',
                'keywords'    => ['new message', 'create message', 'message template', 'email template'],
                'action_type' => 'navigate_url_new_tab',
                'action_payload' => [
                    'url' => admin_url('admin.php?page=griffinforms-message'),
                ],
            ],
            [
                'id'          => 'new_folder',
                'label'       => __('New Folder', 'griffinforms-form-builder'),
                'description' => __('Create a new folder for organizing forms', 'griffinforms-form-builder'),
                'icon'        => 'folder',
                'keywords'    => ['new folder', 'create folder', 'add folder', 'folder'],
                'action_type' => 'navigate_url_new_tab',
                'action_payload' => [
                    'url' => admin_url('admin.php?page=griffinforms-folder'),
                ],
            ],
            [
                'id'          => 'new_theme',
                'label'       => __('New Theme', 'griffinforms-form-builder'),
                'description' => __('Create a new form theme', 'griffinforms-form-builder'),
                'icon'        => 'theme',
                'keywords'    => ['new theme', 'create theme', 'add theme', 'form theme'],
                'action_type' => 'navigate_url_new_tab',
                'action_payload' => [
                    'url' => admin_url('admin.php?page=griffinforms-formtheme'),
                ],
            ],
        ];

        if ($form_id > 0) {
            $entries[] = [
                'id'          => 'edit_with_ai',
                'label'       => __('Edit with AI', 'griffinforms-form-builder'),
                'description' => __('Open this form in AI edit mode', 'griffinforms-form-builder'),
                'icon'        => 'form',
                'keywords'    => ['edit with ai', 'ai edit', 'ai draft', 'assist', 'butler'],
                'action_type' => 'navigate_url',
                'action_payload' => [
                    'url' => admin_url('admin.php?page=griffinforms-app&form_id=' . absint($form_id) . '&mode=ai_draft'),
                ],
            ];
        }

        $results = [];
        foreach ($entries as $entry) {
            $matched = stripos($entry['label'], $query) !== false
                || stripos($entry['description'], $query) !== false;

            if (!$matched) {
                foreach ($entry['keywords'] as $kw) {
                    if (stripos($kw, $query) !== false) {
                        $matched = true;
                        break;
                    }
                }
            }

            if (!$matched) {
                continue;
            }

            $results[] = new SearchResultItem(
                result_id:      'create_' . $entry['id'],
                provider_id:    $this->getProviderId(),
                label:          $entry['label'],
                action_type:    $entry['action_type'],
                action_payload: $entry['action_payload'],
                description:    $entry['description'],
                icon:           $entry['icon'],
                score:          0
            );
        }

        return $results;
    }

    private function getNextFormNumber(): int
    {
        global $wpdb;

        $table = $this->config->getTable('form');
        if (!$table) {
            return 1;
        }

        $next = $wpdb->get_var($wpdb->prepare(
            "SELECT COALESCE(MAX(id), 0) + 1 FROM %i",
            $table
        ));

        return max(1, absint($next));
    }
}
