<div x-data="settings">
    <!-- Tabs Header -->
    <div class="border-b border-gray-200 mb-6">
        <nav class="-mb-px flex space-x-8" aria-label="Tabs">
            <button @click="activeTab = 'interactions'"
                :class="activeTab === 'interactions' ? 'border-primary-500 text-primary-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors">
                Interações
            </button>
            <button @click="activeTab = 'pangolin'"
                :class="activeTab === 'pangolin' ? 'border-primary-500 text-primary-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors">
                Pangolin Proxy
            </button>
        </nav>
    </div>

    <!-- Interactions Tab -->
    <div x-show="activeTab === 'interactions'" x-transition:enter="transition ease-out duration-200"
        x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0">

        <div class="max-w-2xl mx-auto bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-6">Telegram</h3>
            <p class="text-sm text-gray-500 mb-6">Configure as notificações automáticas para o Telegram.</p>

            <form action="/admin/settings/update" method="POST">
                <div class="space-y-4">

                    <!-- Bot Token -->
                    <div>
                        <label for="telegram_bot_token" class="block text-sm font-medium text-gray-700 mb-1">Bot
                            Token</label>
                        <input type="text" name="telegram_bot_token" id="telegram_bot_token"
                            value="<?= htmlspecialchars($settings['telegram_bot_token'] ?? '') ?>"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                            placeholder="123456789:ABCdefGHIjklMNOpqRSTuvwXYZ">
                        <p class="mt-1 text-sm text-gray-500">O token fornecido pelo @BotFather.</p>
                    </div>

                    <!-- Chat ID -->
                    <div>
                        <label for="telegram_chat_id" class="block text-sm font-medium text-gray-700 mb-1">Chat
                            ID</label>
                        <input type="text" name="telegram_chat_id" id="telegram_chat_id"
                            value="<?= htmlspecialchars($settings['telegram_chat_id'] ?? '') ?>"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                            placeholder="-1001234567890">
                        <p class="mt-1 text-sm text-gray-500">ID do canal ou grupo para onde as mensagens serão
                            enviadas.</p>
                    </div>

                    <!-- Message Template -->
                    <div>
                        <label for="telegram_message_template"
                            class="block text-sm font-medium text-gray-700 mb-1">Modelo de Mensagem</label>
                        <textarea id="telegram_message_template" name="telegram_message_template" rows="5"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                            placeholder="Nova ordem cadastrada!"><?= htmlspecialchars($settings['telegram_message_template'] ?? "<b>Nova Ordem Cadastrada!</b>\n\n<b>Título:</b> {title}\n<b>Tipo:</b> {type}\n<b>Domínios:</b> {total_domains}") ?></textarea>
                        <p class="mt-2 text-sm text-gray-500">
                            Variáveis disponíveis: <code class="bg-gray-100 px-1 rounded">{title}</code>,
                            <code class="bg-gray-100 px-1 rounded">{type}</code>,
                            <code class="bg-gray-100 px-1 rounded">{total_domains}</code>,
                            <code class="bg-gray-100 px-1 rounded">{order_id}</code>.
                            Suporta HTML (negrito, itálico, etc).
                        </p>
                    </div>

                </div>

                <div class="mt-6 flex justify-end space-x-3">
                    <button type="button" @click="testIntegration()" :disabled="testing"
                        class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center">
                        <svg x-show="testing" class="animate-spin -ml-1 mr-3 h-5 w-5 text-gray-700"
                            xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4">
                            </circle>
                            <path class="opacity-75" fill="currentColor"
                                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
                            </path>
                        </svg>
                        <span x-text="testing ? 'Enviando...' : 'Testar Integração'"></span>
                    </button>
                    <button type="submit"
                        class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors">
                        Salvar Configurações
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Pangolin Tab -->
    <div x-show="activeTab === 'pangolin'" x-transition:enter="transition ease-out duration-200"
        x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0"
        style="display: none;">

        <div class="max-w-2xl mx-auto bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-6">Pangolin Proxy</h3>
            <p class="text-sm text-gray-500 mb-6">Configure a integração com o Pangolin para gerenciar permissões de
                acesso baseadas no ASN.</p>

            <form action="/admin/settings/update" method="POST">
                <div class="space-y-4">

                    <!-- Enable -->
                    <div class="flex items-center">
                        <input type="hidden" name="pangolin_enabled" value="0">
                        <input type="checkbox" name="pangolin_enabled" id="pangolin_enabled" value="1"
                            <?= ($settings['pangolin_enabled'] ?? '0') === '1' ? 'checked' : '' ?>
                            class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded">
                        <label for="pangolin_enabled" class="ml-2 block text-sm text-gray-900">
                            Ativar Integração
                        </label>
                    </div>

                    <!-- API URL -->
                    <div>
                        <label for="pangolin_url" class="block text-sm font-medium text-gray-700 mb-1">URL da
                            API</label>
                        <input type="text" name="pangolin_url" id="pangolin_url"
                            value="<?= htmlspecialchars($settings['pangolin_url'] ?? '') ?>"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                            placeholder="https://api.pangolin.net/v1">
                    </div>

                    <!-- API Token -->
                    <div>
                        <label for="pangolin_token" class="block text-sm font-medium text-gray-700 mb-1">API
                            Token</label>
                        <input type="password" name="pangolin_token" id="pangolin_token"
                            value="<?= htmlspecialchars($settings['pangolin_token'] ?? '') ?>"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                            placeholder="Seu token de acesso">
                    </div>

                    <!-- Org ID -->
                    <div>
                        <label for="pangolin_org_id" class="block text-sm font-medium text-gray-700 mb-1">Organization ID</label>
                        <input type="text" name="pangolin_org_id" id="pangolin_org_id"
                            value="<?= htmlspecialchars($settings['pangolin_org_id'] ?? '') ?>"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                            placeholder="ipv0">
                        <p class="mt-1 text-sm text-gray-500">O identificador da organização (ex: na URL /ipv0/settings/... seria "ipv0").</p>
                    </div>

                    <!-- Resource Name -->
                    <div>
                        <label for="pangolin_resource_name" class="block text-sm font-medium text-gray-700 mb-1">Resource Name (Slug)</label>
                        <input type="text" name="pangolin_resource_name" id="pangolin_resource_name"
                            value="<?= htmlspecialchars($settings['pangolin_resource_name'] ?? '') ?>"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                            placeholder="cooperative-plains-pocket-gopher">
                        <p class="mt-1 text-sm text-gray-500">O nome do resource na URL (slug). Ex: na URL /resources/cooperative-plains-pocket-gopher/... seria "cooperative-plains-pocket-gopher".</p>
                    </div>

                </div>

                <div class="mt-6 flex justify-end space-x-3">
                    <button type="submit"
                        class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors">
                        Salvar Configurações
                    </button>
                </div>
            </form>
        </div>
    </div>


</div>

<script>
    document.addEventListener('alpine:init', () => {
        Alpine.data('settings', () => ({
            activeTab: '<?= isset($_GET['tab']) ? $_GET['tab'] : 'interactions' ?>',
            testing: false,

            testIntegration() {

                this.testing = true;

                // Save settings first via AJAX if needed, but for now we assume saved settings
                // Or we could send form data. Let's send form data to ensure we test what's typed.
                const form = document.querySelector('form');
                const formData = new FormData(form);

                // We need to update settings first? 
                // The requirement implies testing the configuration. 
                // Usually "Test" uses the saved config or the current input.
                // Let's assume we test the SAVED config for simplicity as per plan, 
                // but user might expect to test what they just typed.
                // To be safe and robust: Update settings then test, OR send values to test endpoint.
                // The plan said "instantiate TelegramService" which uses DB.
                // So the user must SAVE first.
                // Let's warn if inputs are dirty? Too complex for now.
                // Let's just call the endpoint.

                fetch('/admin/settings/test-telegram', {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                    .then(async response => {
                        const text = await response.text();
                        try {
                            return JSON.parse(text);
                        } catch (e) {
                            throw new Error(`Resposta inválida do servidor (${response.status}): ${text.substring(0, 100)}...`);
                        }
                    })
                    .then(data => {
                        this.$dispatch('notify', {
                            type: data.success ? 'success' : 'error',
                            title: data.success ? 'Sucesso' : 'Erro',
                            message: data.message
                        });
                    })
                    .catch(error => {
                        console.error('Erro no teste:', error);
                        this.$dispatch('notify', {
                            type: 'error',
                            title: 'Erro',
                            message: 'Erro: ' + error.message
                        });
                    })
                    .finally(() => {
                        this.testing = false;
                    });
            }
        }))
    })
</script>