{% extends 'layouts/admin.twig' %}

{% block content %}
    {% include 'wisebee/admin/partials/_wisebeeSettingsStyles.twig' %}

    <style>
        /* Wizard-specific styles */
        .wizard-container {
            max-width: 900px;
        }

        /* Step Indicators */
        .step-indicators {
            display: flex;
            align-items: center;
            margin-bottom: 30px;
            padding: 0;
            list-style: none;
            gap: 8px;
        }
        .step-indicators .step {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 16px;
            background: #f5f5f5;
            border-radius: 6px;
            color: #888;
            font-size: 14px;
            transition: all 0.2s;
        }
        .step-indicators .step.active {
            background: #3498db;
            color: #fff;
            font-weight: 600;
        }
        .step-indicators .step.completed {
            background: #27ae60;
            color: #fff;
        }
        .step-indicators .step-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background: rgba(0,0,0,0.1);
            font-size: 12px;
            font-weight: 600;
        }
        .step-indicators .step.active .step-number,
        .step-indicators .step.completed .step-number {
            background: rgba(255,255,255,0.3);
        }
        .step-indicators .arrow {
            color: #ccc;
            font-size: 18px;
        }

        /* Config Display */
        .wizard-container .config-display {
            background: #f8f9fa;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 16px;
            font-size: 13px;
            line-height: 1.6;
        }
        .wizard-container .config-display strong {
            color: #27ae60;
        }
        .wizard-container .config-display code {
            background: #eee;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
        }

        /* Summary Table */
        .wizard-container .summary-table {
            width: 100%;
            max-width: 500px;
            border-collapse: collapse;
        }
        .wizard-container .summary-table td {
            padding: 10px 12px;
            border-bottom: 1px solid #eee;
            font-size: 14px;
        }
        .wizard-container .summary-table td:first-child {
            font-weight: 500;
            color: #555;
            width: 140px;
        }
    </style>

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Admin</a> /</li>
        <li><a href="/admin/wisebee/consultations">Wisebee</a> /</li>
        <li class="end">Setup</li>
    </ul>
    <h1>Wisebee Setup</h1>

    <div class="wizard-container wisebee-settings">

    <div id="wizard-error" class="alert alert-error" style="display:none;"></div>

    {# Step indicators #}
    <div class="step-indicators">
        <div id="step-indicator-1" class="step active">
            <span class="step-number">1</span>
            <span>Create Client</span>
        </div>
        <span class="arrow">&rarr;</span>
        <div id="step-indicator-2" class="step">
            <span class="step-number">2</span>
            <span>Configure Settings</span>
        </div>
        <span class="arrow">&rarr;</span>
        <div id="step-indicator-3" class="step">
            <span class="step-number">3</span>
            <span>Complete</span>
        </div>
    </div>

    {# ==================== STEP 1: Provision ==================== #}
    <div id="step-1">
        {% if isConfigured %}
            <div class="config-display">
                <strong>Wisebee is already configured.</strong><br><br>
                Host: <code>{{ currentHost }}</code><br>
                Booking Widget Key: <code>{{ currentBookingWidgetKey }}</code><br>
                Consultation Widget Key: <code>{{ currentConsultationWidgetKey }}</code>
            </div>
            <p style="margin: 16px 0; color: #555;">Provisioning is disabled because a Wisebee client already exists. You can proceed to configure settings or view the summary.</p>
            <div class="actions-row" style="border-top: none; margin-top: 0; padding-top: 0;">
                <button type="button" class="btn-primary" onclick="showStep(2)">Configure Settings</button>
                <button type="button" class="btn-secondary" onclick="showStep(3)">View Summary</button>
            </div>
        {% else %}
            <form id="provision-form" onsubmit="return submitProvision(event)">
                <fieldset>
                    <legend>Create Wisebee Client</legend>

                    {% if not hasProvisioningKey %}
                    <div class="setting-row">
                        <label class="setting-label" for="provisioning_key">Provisioning Key</label>
                        <input type="text" class="setting-input" name="provisioning_key" id="provisioning_key" required autocomplete="off">
                        <p class="setting-help">This key must match the <code>PROVISIONING_KEY</code> set on the Wisebee server. It will be saved to your <code>.env</code> file. You can find it in the MTC Vault</p>
                    </div>
                    <div class="setting-row" style="border-bottom: none;">
                        <button type="button" class="btn-secondary" onclick="confirmProvisioningKey()">Continue</button>
                    </div>
                    {% endif %}

                    <div id="provision-fields" {% if not hasProvisioningKey %}style="display:none;"{% endif %}>
                    <div class="setting-row">
                        <label class="setting-label" for="admin_user">Admin User (Owner)</label>
                        <select class="setting-input" name="admin_user" id="admin_user" required>
                            <option value="">-- Select Admin User --</option>
                            {% for user in adminUsers %}
                                <option value="{{ user.id }}"
                                        data-email="{{ user.email }}"
                                        data-name="{{ user.name }}">
                                    {{ user.name }} ({{ user.email }})
                                </option>
                            {% endfor %}
                        </select>
                        <p class="setting-help">This admin user will be linked as the owner of the Wisebee tenant. Their email will be used for the Wisebee login.</p>
                    </div>

                    <div class="setting-row">
                        <label class="setting-label" for="owner_firstname">First Name</label>
                        <input type="text" class="setting-input" name="owner_firstname" id="owner_firstname" required>
                        <p class="setting-help">First name for the owner account on Wisebee.</p>
                    </div>

                    <div class="setting-row">
                        <label class="setting-label" for="owner_lastname">Last Name</label>
                        <input type="text" class="setting-input" name="owner_lastname" id="owner_lastname" required>
                        <p class="setting-help">Last name for the owner account on Wisebee.</p>
                    </div>

                    <div class="setting-row">
                        <label class="setting-label" for="owner_phone">Phone</label>
                        <input type="text" class="setting-input" name="owner_phone" id="owner_phone" required>
                        <p class="setting-help">Contact phone number for the owner account.</p>
                    </div>

                    <div class="setting-row">
                        <label class="setting-label" for="environment">Environment</label>
                        <select class="setting-input" name="environment" id="environment" required onchange="loadIndustries()">
                            <option value="">-- Select Environment --</option>
                            {% for domain, label in environments %}
                                <option value="{{ domain }}">{{ label }} ({{ domain }})</option>
                            {% endfor %}
                        </select>
                        <p class="setting-help">The Wisebee server to create the tenant on. Use Staging for testing or Live for production.</p>
                    </div>

                    <div class="setting-row">
                        <label class="setting-label" for="client_name">Client Name</label>
                        <input type="text" class="setting-input" name="client_name" id="client_name" required>
                        <p class="setting-help">The business name shown within Wisebee (e.g. "My Pharmacy").</p>
                    </div>

                    <div class="setting-row">
                        <label class="setting-label" for="client_code">Subdomain Code</label>
                        <input type="text" class="setting-input" name="client_code" id="client_code" required
                               pattern="[a-zA-Z0-9\-_]+" title="Only letters, numbers, hyphens, and underscores">
                        <p class="setting-help">Creates a new tenant at <code>{code}.{environment}</code>. Use lowercase letters, numbers, and hyphens only (e.g. "my-pharmacy").</p>
                    </div>

                    <div class="setting-row">
                        <label class="setting-label" for="industry_id">Industry</label>
                        <select class="setting-input" name="industry_id" id="industry_id" required disabled>
                            <option value="">-- Select an environment first --</option>
                        </select>
                        <p class="setting-help">Select the industry category for this client. Options are loaded from the selected environment.</p>
                    </div>

                    <div class="setting-row" style="border-bottom: none;">
                        <label class="setting-label" for="owner_password">Owner Password</label>
                        <input type="password" class="setting-input" name="owner_password" id="owner_password" required minlength="8">
                        <p class="setting-help">Password for the initial Wisebee admin account. Minimum 8 characters.</p>
                    </div>

                    <div class="actions-row">
                        <input type="submit" value="Create Client" class="btn-primary" id="provision-submit">
                    </div>
                    </div>{# /provision-fields #}
                </fieldset>
            </form>
        {% endif %}
    </div>

    {# ==================== STEP 2: Configure Settings ==================== #}
    <div id="step-2" style="display:none;">
        <form id="settings-form" onsubmit="return submitSettings(event)">

            {% include 'wisebee/admin/partials/_wisebeeSettingsFields.twig' with {
                idPrefix: 'wizard_',
                namePrefix: '',
                nameSuffix: '',
                defaults: {
                    bookingUrl: bookingUrl,
                    consultationUrl: consultationUrl,
                    websiteUrl: websiteUrl,
                    paymentRedirectUrl: paymentRedirectUrl,
                    webhookUrl: webhookUrl
                }
            } %}

            <div class="actions-row">
                <input type="submit" value="Save Settings" class="btn-primary" id="settings-submit">
            </div>
        </form>
    </div>

    {# ==================== STEP 3: Complete ==================== #}
    <div id="step-3" style="display:none;">
        <div class="alert alert-success">
            <strong>Setup Complete!</strong> Your Wisebee client has been configured successfully.
        </div>

        <table class="summary-table">
            <tr>
                <td>Domain</td>
                <td id="summary-domain">{% if isConfigured %}{{ currentHost }}{% endif %}</td>
            </tr>
            <tr>
                <td>Host URL</td>
                <td id="summary-host">{% if isConfigured %}{{ currentHost }}{% endif %}</td>
            </tr>
        </table>

        <div class="actions-row">
            <a id="link-wisebee-admin" href="{% if isConfigured %}{{ currentHost|trim('/') }}/login{% else %}#{% endif %}" target="_blank" class="btn-primary">
                Open Wisebee Admin
            </a>
            <a href="{{ route('wisebee-admin-remote-settings') }}" class="btn-secondary">
                Remote Settings
            </a>
        </div>
    </div>

    </div>{# /.wizard-container #}

    {% include 'wisebee/admin/partials/_wisebeeSettingsScripts.twig' with {
        idPrefix: 'wizard_',
        uploadUrl: '/admin/wisebee/setup/upload-logo',
        errorElementId: 'wizard-error'
    } %}

    <script>
        var provisionData = null;

        function confirmProvisioningKey() {
            var key = document.getElementById('provisioning_key').value.trim();
            if (!key) {
                showError('Please enter a provisioning key.');
                return;
            }
            hideError();
            document.getElementById('provision-fields').style.display = '';
        }

        function loadIndustries() {
            var environment = document.getElementById('environment').value;
            var select = document.getElementById('industry_id');

            if (!environment) {
                select.innerHTML = '<option value="">-- Select an environment first --</option>';
                select.disabled = true;
                return;
            }

            select.innerHTML = '<option value="">Loading...</option>';
            select.disabled = true;

            var provisioningKeyField = document.getElementById('provisioning_key');
            var url = '/admin/wisebee/setup/industries?environment=' + encodeURIComponent(environment);
            if (provisioningKeyField && provisioningKeyField.value) {
                url += '&provisioning_key=' + encodeURIComponent(provisioningKeyField.value);
            }

            fetch(url, {
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(function(response) { return response.json(); })
            .then(function(result) {
                if (result.success && result.data) {
                    var html = '<option value="">-- Select Industry --</option>';
                    for (var i = 0; i < result.data.length; i++) {
                        html += '<option value="' + result.data[i].id + '">' + result.data[i].name + '</option>';
                    }
                    select.innerHTML = html;
                    select.disabled = false;
                } else {
                    select.innerHTML = '<option value="">-- Failed to load industries --</option>';
                    showError(result.error || 'Failed to load industries');
                }
            })
            .catch(function(err) {
                select.innerHTML = '<option value="">-- Failed to load industries --</option>';
                showError('Connection error: ' + err.message);
            });
        }

        function showStep(step) {
            document.getElementById('step-1').style.display = step === 1 ? 'block' : 'none';
            document.getElementById('step-2').style.display = step === 2 ? 'block' : 'none';
            document.getElementById('step-3').style.display = step === 3 ? 'block' : 'none';

            for (var i = 1; i <= 3; i++) {
                var indicator = document.getElementById('step-indicator-' + i);
                indicator.classList.remove('active', 'completed');
                if (i < step) {
                    indicator.classList.add('completed');
                } else if (i === step) {
                    indicator.classList.add('active');
                }
            }

            hideError();

            // Initialize color pickers when showing step 2
            if (step === 2) {
                wisebeeInitColorPickers('wizard_');
            }
        }

        function showError(message) {
            var el = document.getElementById('wizard-error');
            el.textContent = typeof message === 'string' ? message : JSON.stringify(message);
            el.style.display = 'block';
        }

        function hideError() {
            document.getElementById('wizard-error').style.display = 'none';
        }

        function submitProvision(e) {
            e.preventDefault();
            hideError();

            var select = document.getElementById('admin_user');
            var selected = select.options[select.selectedIndex];

            var provisioningKeyField = document.getElementById('provisioning_key');

            var data = {
                admin_user_id: parseInt(select.value),
                environment: document.getElementById('environment').value,
                name: document.getElementById('client_name').value,
                code: document.getElementById('client_code').value,
                email: selected.getAttribute('data-email'),
                firstname: document.getElementById('owner_firstname').value,
                lastname: document.getElementById('owner_lastname').value,
                phone: document.getElementById('owner_phone').value,
                password: document.getElementById('owner_password').value,
                industry_id: parseInt(document.getElementById('industry_id').value)
            };

            if (provisioningKeyField) {
                data.provisioning_key = provisioningKeyField.value;
            }

            var btn = document.getElementById('provision-submit');
            btn.disabled = true;
            btn.value = 'Creating...';

            fetch('/admin/wisebee/setup/provision', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(function(response) { return response.json(); })
            .then(function(result) {
                btn.disabled = false;
                btn.value = 'Create Client';

                if (result.success) {
                    provisionData = result.data;
                    document.getElementById('summary-domain').textContent = result.data.domain;
                    document.getElementById('summary-host').textContent = result.data.host;
                    document.getElementById('link-wisebee-admin').href = result.data.host.replace(/\/?$/, '/') + 'login';
                    showStep(2);
                } else {
                    showError(result.error || 'Provisioning failed');
                }
            })
            .catch(function(err) {
                btn.disabled = false;
                btn.value = 'Create Client';
                showError('Connection error: ' + err.message);
            });

            return false;
        }

        function submitSettings(e, retryCount) {
            e.preventDefault();
            hideError();
            retryCount = retryCount || 0;

            var form = document.getElementById('settings-form');
            var inputs = form.querySelectorAll('input[name], select[name]');
            var settings = {};

            // Collect all settings from the form
            for (var i = 0; i < inputs.length; i++) {
                var input = inputs[i];
                var name = input.name;
                if (!name) continue;

                if (input.type === 'checkbox') {
                    if (input.disabled) continue;
                    settings[name] = input.checked ? '1' : '0';
                } else if (input.type === 'hidden') {
                    if (!(name in settings)) {
                        settings[name] = input.value;
                    }
                } else if (input.type !== 'file') {
                    settings[name] = input.value;
                }
            }

            var btn = document.getElementById('settings-submit');
            btn.disabled = true;
            btn.value = retryCount > 0 ? 'Retrying...' : 'Saving...';

            // Include admin_user_id and owner_email for user linking (from provision step)
            var payload = { settings: settings };
            if (provisionData && provisionData.admin_user_id) {
                payload.admin_user_id = provisionData.admin_user_id;
                payload.owner_email = provisionData.owner_email;
            }

            fetch('/admin/wisebee/setup/configure', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(payload)
            })
            .then(function(response) { return response.json(); })
            .then(function(result) {
                if (result.success) {
                    btn.disabled = false;
                    btn.value = 'Save Settings';
                    showStep(3);
                } else if (retryCount < 2) {
                    // Retry after delay (tenant might not be ready yet)
                    btn.value = 'Waiting for tenant...';
                    setTimeout(function() {
                        submitSettings(e, retryCount + 1);
                    }, 2000);
                } else {
                    btn.disabled = false;
                    btn.value = 'Save Settings';
                    showError(result.error || 'Failed to save settings');
                }
            })
            .catch(function(err) {
                if (retryCount < 2) {
                    btn.value = 'Waiting for tenant...';
                    setTimeout(function() {
                        submitSettings(e, retryCount + 1);
                    }, 2000);
                } else {
                    btn.disabled = false;
                    btn.value = 'Save Settings';
                    showError('Connection error: ' + err.message);
                }
            });

            return false;
        }
    </script>
{% endblock %}
