<script setup>
/**
 * Admin Email Template Editor
 */
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Head, Link, useForm, router } from '@inertiajs/vue3';
import { ref } from 'vue';

const props = defineProps({
    template: Object,
});

const form = useForm({
    subject: props.template.subject,
    body: props.template.body,
    is_active: props.template.is_active,
});

const testEmail = ref('');
const sendingTest = ref(false);
const showTestModal = ref(false);

const insertVariable = (variable) => {
    const textarea = document.getElementById('template-body');
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = form.body;
    const before = text.substring(0, start);
    const after = text.substring(end, text.length);
    form.body = before + `{{${variable}}}` + after;
    
    setTimeout(() => {
        textarea.focus();
        textarea.setSelectionRange(start + variable.length + 4, start + variable.length + 4);
    }, 10);
};

const submit = () => {
    form.put(route('admin.email-templates.update', props.template.id));
};

const sendTestEmail = () => {
    if (!testEmail.value) return;
    sendingTest.value = true;
    router.post(route('admin.email-templates.test', props.template.id), {
        email: testEmail.value
    }, {
        onFinish: () => {
            sendingTest.value = false;
            showTestModal.value = false;
            testEmail.value = '';
        }
    });
};

const formatVariable = (variable) => '{{' + variable + '}}';
</script>

<template>
    <Head :title="`Editar: ${template.name}`" />

    <AdminLayout>
        <div class="py-6">
            <!-- Header -->
            <div class="mb-6 px-4 sm:px-0">
                <div class="flex items-center justify-between">
                    <div>
                        <Link :href="route('admin.email-templates.index')" class="text-sm text-blue-600 hover:text-blue-800 dark:text-blue-400 flex items-center gap-1 mb-2">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                            </svg>
                            Volver a plantillas
                        </Link>
                        <h1 class="text-2xl font-bold text-gray-900 dark:text-white">{{ template.name }}</h1>
                        <p class="text-sm text-gray-500 dark:text-gray-400 font-mono">{{ template.slug }}</p>
                    </div>
                    <div class="flex items-center gap-3">
                        <a 
                            :href="route('admin.email-templates.preview', template.id)"
                            target="_blank"
                            class="inline-flex items-center px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                        >
                            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                            </svg>
                            Vista previa
                        </a>
                        <button 
                            @click="showTestModal = true"
                            class="inline-flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
                        >
                            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                            </svg>
                            Enviar prueba
                        </button>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Editor Principal -->
                <div class="lg:col-span-2 bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden">
                    <form @submit.prevent="submit" class="p-6 space-y-6">
                        <!-- Status Toggle -->
                        <div class="flex items-center justify-between pb-4 border-b border-gray-100 dark:border-gray-700">
                            <span class="text-sm font-medium text-gray-700 dark:text-gray-300">Estado de la plantilla</span>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" v-model="form.is_active" class="sr-only peer">
                                <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
                                <span class="ml-3 text-sm font-medium text-gray-900 dark:text-gray-300">
                                    {{ form.is_active ? 'Activa' : 'Inactiva' }}
                                </span>
                            </label>
                        </div>

                        <!-- Subject -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Asunto del Correo
                            </label>
                            <input
                                v-model="form.subject"
                                type="text"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                required
                            />
                        </div>

                        <!-- Body -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Contenido HTML
                            </label>
                            <textarea
                                id="template-body"
                                v-model="form.body"
                                rows="20"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-blue-500 focus:ring-blue-500 font-mono text-sm"
                                required
                            ></textarea>
                        </div>

                        <!-- Submit -->
                        <div class="flex items-center justify-end pt-4 border-t border-gray-100 dark:border-gray-700">
                            <button
                                type="submit"
                                :disabled="form.processing"
                                class="inline-flex items-center px-6 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors disabled:opacity-50"
                            >
                                <svg v-if="form.processing" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" 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>
                                Guardar Cambios
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Sidebar - Variables -->
                <div class="lg:col-span-1">
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6 sticky top-6">
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                            Variables Disponibles
                        </h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
                            Haz clic para insertar en el editor:
                        </p>
                        <div class="space-y-2">
                            <button
                                v-for="variable in template.variables"
                                :key="variable"
                                type="button"
                                @click="insertVariable(variable)"
                                class="w-full text-left px-3 py-2 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 text-sm rounded-lg hover:bg-blue-100 dark:hover:bg-blue-900/40 transition-colors font-mono flex items-center justify-between"
                            >
                                <span>{{ formatVariable(variable) }}</span>
                                <svg class="w-4 h-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                                </svg>
                            </button>
                        </div>

                        <div class="mt-6 pt-6 border-t border-gray-100 dark:border-gray-700">
                            <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Consejos</h4>
                            <ul class="text-xs text-gray-500 dark:text-gray-400 space-y-2">
                                <li>• Las variables se reemplazan automáticamente</li>
                                <li>• Usa HTML válido para mejor compatibilidad</li>
                                <li>• Prueba el email antes de activar cambios</li>
                                <li>• Usa estilos inline para emails</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Test Email Modal -->
        <Teleport to="body">
            <div v-if="showTestModal" class="fixed inset-0 z-50 overflow-y-auto">
                <div class="flex items-center justify-center min-h-screen px-4">
                    <div class="fixed inset-0 bg-black/50 transition-opacity" @click="showTestModal = false"></div>
                    
                    <div class="relative bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full p-6">
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                            Enviar Email de Prueba
                        </h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
                            Enviaremos un email de prueba con datos de ejemplo.
                        </p>
                        
                        <input
                            v-model="testEmail"
                            type="email"
                            placeholder="correo@ejemplo.com"
                            class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white mb-4"
                            @keyup.enter="sendTestEmail"
                        />
                        
                        <div class="flex justify-end gap-3">
                            <button 
                                @click="showTestModal = false"
                                class="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                            >
                                Cancelar
                            </button>
                            <button 
                                @click="sendTestEmail"
                                :disabled="sendingTest || !testEmail"
                                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
                            >
                                {{ sendingTest ? 'Enviando...' : 'Enviar' }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>
