<?php
/**
 * Configuration Edit View
 *
 * @package SlideMind
 * @since 2.0.0
 */

if (!defined('ABSPATH')) {
    exit;
}

if (!current_user_can('manage_slidemind_configs')) {
    wp_die(esc_html__('You do not have permission to access this page.', 'slidemind'));
}

$plugin = \SlideMind\Plugin::instance();
$config_repo = $plugin->get_config_repository();
$llm_proxy = $plugin->get_llm_proxy();

// Edit or create mode.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only navigation param; capability checked above; value cast to int.
$config_id = isset($_GET['config_id']) ? (int) $_GET['config_id'] : 0;
$config = $config_id ? $config_repo->get_by_id($config_id) : null;

$is_edit = !empty($config);
$page_title = $is_edit ? __('Edit configuration', 'slidemind') : __('New configuration', 'slidemind');

// Fetch models
$models = $llm_proxy->get_models();

// Default values
$defaults = [
    'title'          => '',
    'course_name' => '',
    'usage_scope'    => 'course',
    'module_info'    => '',
    'slide_info'     => '',
    'model_id'       => 'anthropic/claude-3.5-sonnet',
    'system_prompt'  => '',
    'temperature'    => 0.7,
    'max_tokens'     => 1024,
    'notes'          => '',
    'status'         => 'draft',
    'config_uid'   => '',
];

$config = $config ? array_merge($defaults, $config) : $defaults;
?>

<div class="sm-wrap">
    <div class="sm-header">
        <h1><?php echo esc_html($page_title); ?></h1>
        <div class="sm-header-actions">
            <a href="<?php echo esc_url(admin_url('admin.php?page=slidemind-configurations')); ?>" class="sm-btn sm-btn-secondary">
                <span class="dashicons dashicons-arrow-left-alt"></span>
                <?php esc_html_e('Back to list', 'slidemind'); ?>
            </a>
        </div>
    </div>

    <form id="sm-config-form">
        <?php if ($config_id): ?>
            <input type="hidden" name="id" value="<?php echo esc_attr($config_id); ?>">
        <?php endif; ?>

        <div style="display: grid; grid-template-columns: 1fr 350px; gap: 24px;">
            <!-- Main column -->
            <div>
                <div class="sm-card">
                    <div class="sm-card-header">
                        <h2 class="sm-card-title"><?php esc_html_e('General information', 'slidemind'); ?></h2>
                    </div>

                    <div class="sm-form-group">
                        <label class="sm-form-label" for="sm-title">
                            <?php esc_html_e('Configuration title', 'slidemind'); ?> <span class="required">*</span>
                        </label>
                        <input type="text"
                               id="sm-title"
                               name="title"
                               class="sm-form-input"
                               value="<?php echo esc_attr($config['title']); ?>"
                               placeholder="<?php esc_attr_e('E.g.: Leadership Module 1 Tutor', 'slidemind'); ?>"
                               required>
                    </div>

                    <div class="sm-form-row">
                        <div class="sm-form-group">
                            <label class="sm-form-label" for="sm-course-name">
                                <?php esc_html_e('Course name', 'slidemind'); ?> <span class="required">*</span>
                            </label>
                            <input type="text"
                                   id="sm-course-name"
                                   name="course_name"
                                   class="sm-form-input"
                                   value="<?php echo esc_attr($config['course_name']); ?>"
                                   placeholder="<?php esc_attr_e('E.g.: Leadership Course', 'slidemind'); ?>"
                                   required>
                        </div>

                        <div class="sm-form-group">
                            <label class="sm-form-label" for="sm-usage-scope">
                                <?php esc_html_e('Scope', 'slidemind'); ?>
                            </label>
                            <select id="sm-usage-scope" name="usage_scope" class="sm-form-select">
                                <option value="course" <?php selected($config['usage_scope'], 'course'); ?>><?php esc_html_e('Course (default)', 'slidemind'); ?></option>
                                <option value="module" <?php selected($config['usage_scope'], 'module'); ?>><?php esc_html_e('Module', 'slidemind'); ?></option>
                                <option value="slide" <?php selected($config['usage_scope'], 'slide'); ?>>Slide</option>
                            </select>
                        </div>
                    </div>

                    <div class="sm-form-row" id="sm-module-field" style="display: none;">
                        <div class="sm-form-group">
                            <label class="sm-form-label" for="sm-module-info">
                                <?php esc_html_e('Module', 'slidemind'); ?>
                            </label>
                            <input type="text"
                                   id="sm-module-info"
                                   name="module_info"
                                   class="sm-form-input"
                                   value="<?php echo esc_attr($config['module_info']); ?>"
                                   placeholder="Ex: Module 1 - Introduction">
                        </div>
                    </div>

                    <div class="sm-form-row" id="sm-slide-field" style="display: none;">
                        <div class="sm-form-group">
                            <label class="sm-form-label" for="sm-slide-info">
                                Slide
                            </label>
                            <input type="text"
                                   id="sm-slide-info"
                                   name="slide_info"
                                   class="sm-form-input"
                                   value="<?php echo esc_attr($config['slide_info']); ?>"
                                   placeholder="Ex: Slide 5 - Quiz">
                        </div>
                    </div>
                </div>

                <div class="sm-card">
                    <div class="sm-card-header">
                        <h2 class="sm-card-title"><?php esc_html_e('Model configuration', 'slidemind'); ?></h2>
                    </div>

                    <div class="sm-form-group">
                        <label class="sm-form-label" for="sm-model-id">
                            <?php esc_html_e('LLM Model', 'slidemind'); ?> <span class="required">*</span>
                        </label>
                        <select id="sm-model-id" name="model_id" class="sm-form-select sm-model-select" required>
                            <option value=""><?php esc_html_e('Select a model...', 'slidemind'); ?></option>
                            <?php
                            $grouped = [];
                            foreach ($models as $model) {
                                $parts = explode('/', $model['id']);
                                $provider = ucfirst($parts[0]);
                                $grouped[$provider][] = $model;
                            }
                            ksort($grouped);

                            foreach ($grouped as $provider => $provider_models):
                            ?>
                                <optgroup label="<?php echo esc_attr($provider); ?>">
                                    <?php foreach ($provider_models as $model): ?>
                                        <option value="<?php echo esc_attr($model['id']); ?>"
                                                <?php selected($config['model_id'], $model['id']); ?>>
                                            <?php echo esc_html($model['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="sm-form-row">
                        <div class="sm-form-group">
                            <label class="sm-form-label" for="sm-temperature">
                                <?php esc_html_e('Temperature', 'slidemind'); ?>
                            </label>
                            <input type="number"
                                   id="sm-temperature"
                                   name="temperature"
                                   class="sm-form-input"
                                   value="<?php echo esc_attr($config['temperature']); ?>"
                                   min="0"
                                   max="2"
                                   step="0.1">
                            <p class="sm-form-help"><?php esc_html_e('0 = deterministic, 2 = creative', 'slidemind'); ?></p>
                        </div>

                        <div class="sm-form-group">
                            <label class="sm-form-label" for="sm-max-tokens">
                                <?php esc_html_e('Maximum tokens', 'slidemind'); ?>
                            </label>
                            <input type="number"
                                   id="sm-max-tokens"
                                   name="max_tokens"
                                   class="sm-form-input"
                                   value="<?php echo esc_attr($config['max_tokens']); ?>"
                                   min="1"
                                   max="128000">
                            <p class="sm-form-help"><?php esc_html_e('Response length limit', 'slidemind'); ?></p>
                        </div>
                    </div>
                </div>

                <div class="sm-card">
                    <div class="sm-card-header">
                        <h2 class="sm-card-title"><?php esc_html_e('System prompt', 'slidemind'); ?></h2>
                        <span class="sm-card-subtitle"><?php esc_html_e('Use {{variable}} for variables', 'slidemind'); ?></span>
                    </div>

                    <div class="sm-form-group">
                        <textarea id="sm-system-prompt"
                                  name="system_prompt"
                                  class="sm-form-textarea"
                                  rows="10"
                                  placeholder="<?php echo esc_attr(__('You are a caring educational tutor helping {{learner_name}} understand the topic {{topic}}. You use the Socratic method to guide the learner.', 'slidemind')); ?>"><?php echo esc_textarea($config['system_prompt']); ?></textarea>
                        <p class="sm-form-help">
                            <?php
                            /* translators: %s: list of variable codes */
                            printf(esc_html__('Available variables: %s, etc.', 'slidemind'), '<code>{{learner_name}}</code>, <code>{{module_theme}}</code>, <code>{{quiz_score}}</code>');
                            ?>
                        </p>
                    </div>
                </div>

                <div class="sm-card">
                    <div class="sm-card-header">
                        <h2 class="sm-card-title"><?php esc_html_e('Notes', 'slidemind'); ?></h2>
                    </div>

                    <div class="sm-form-group">
                        <textarea id="sm-notes"
                                  name="notes"
                                  class="sm-form-textarea"
                                  rows="3"
                                  placeholder="<?php esc_attr_e('Internal notes (not visible to learners)', 'slidemind'); ?>"><?php echo esc_textarea($config['notes']); ?></textarea>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div>
                <div class="sm-card">
                    <div class="sm-card-header">
                        <h2 class="sm-card-title"><?php esc_html_e('Publishing', 'slidemind'); ?></h2>
                    </div>

                    <div class="sm-form-group">
                        <label class="sm-form-label" for="sm-status"><?php esc_html_e('Status', 'slidemind'); ?></label>
                        <select id="sm-status" name="status" class="sm-form-select">
                            <option value="draft" <?php selected($config['status'], 'draft'); ?>><?php esc_html_e('Draft', 'slidemind'); ?></option>
                            <option value="publish" <?php selected($config['status'], 'publish'); ?>><?php esc_html_e('Published', 'slidemind'); ?></option>
                        </select>
                    </div>

                    <button type="submit" class="sm-btn sm-btn-primary" style="width: 100%;">
                        <?php echo $is_edit ? esc_html__('Update', 'slidemind') : esc_html__('Create configuration', 'slidemind'); ?>
                    </button>
                </div>

                <?php if ($is_edit && $config['config_uid']): ?>
                <div class="sm-card">
                    <div class="sm-card-header">
                        <h2 class="sm-card-title"><?php esc_html_e('Configuration ID', 'slidemind'); ?></h2>
                    </div>

                    <div class="sm-copyable" style="width: 100%; justify-content: space-between;">
                        <code id="sm-config-uid-display"><?php echo esc_html($config['config_uid']); ?></code>
                        <button type="button" class="sm-copyable-btn" data-slug="<?php echo esc_attr($config['config_uid']); ?>">
                            <span class="dashicons dashicons-clipboard"></span>
                        </button>
                    </div>
                    <p class="sm-form-help" style="margin-top: 8px;">
                        <?php esc_html_e('Use this ID in your e-learning project', 'slidemind'); ?>
                    </p>
                </div>
                <?php endif; ?>

                <div class="sm-card">
                    <div class="sm-card-header">
                        <h2 class="sm-card-title"><?php esc_html_e('Specific API key', 'slidemind'); ?></h2>
                    </div>

                    <div class="sm-form-group">
                        <label class="sm-form-label" for="sm-api-key">
                            <?php esc_html_e('API Key (optional)', 'slidemind'); ?>
                        </label>
                        <input type="password"
                               id="sm-api-key"
                               name="api_key"
                               class="sm-form-input"
                               placeholder="<?php esc_attr_e('Leave empty to use the global key', 'slidemind'); ?>">
                        <p class="sm-form-help">
                            <?php esc_html_e('If empty, uses the global API key', 'slidemind'); ?>
                        </p>
                    </div>
                </div>

                <?php if ($is_edit): ?>
                <div class="sm-card">
                    <div class="sm-card-header">
                        <h2 class="sm-card-title"><?php esc_html_e('Actions', 'slidemind'); ?></h2>
                    </div>

                    <a href="<?php echo esc_url(admin_url('admin.php?page=slidemind-sandbox&config_id=' . $config_id)); ?>"
                       class="sm-btn sm-btn-secondary" style="width: 100%; margin-bottom: 12px;">
                        <span class="dashicons dashicons-visibility"></span>
                        <?php esc_html_e('Test in Sandbox', 'slidemind'); ?>
                    </a>

                    <button type="button"
                            class="sm-btn sm-btn-danger sm-delete-config"
                            data-config-id="<?php echo esc_attr($config_id); ?>"
                            style="width: 100%;">
                        <span class="dashicons dashicons-trash"></span>
                        <?php esc_html_e('Delete', 'slidemind'); ?>
                    </button>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>
