<script setup>
/**
 * Admin Post Create/Edit Form
 */
import AdminLayout from '@/Layouts/AdminLayout.vue';
import TiptapEditor from '@/Components/TiptapEditor.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { ref, computed, watch } from 'vue';

const props = defineProps({
    post: {
        type: Object,
        default: null,
    },
    categories: Array,
    tags: Array,
});

const isEditing = computed(() => !!props.post);

const form = useForm({
    _method: props.post ? 'PUT' : undefined,
    title: props.post?.title || '',
    slug: props.post?.slug || '',
    excerpt: props.post?.excerpt || '',
    content: props.post?.content || '',
    category_id: props.post?.category_id || '',
    tags: props.post?.tags?.map(t => t.id) || [],
    featured_image: null,
    meta_title: props.post?.meta_title || '',
    meta_description: props.post?.meta_description || '',
    is_published: props.post?.is_published || false,
});

const imagePreview = ref(props.post?.featured_image ? `/storage/${props.post.featured_image}` : null);

const handleImageChange = (event) => {
    const file = event.target.files[0];
    if (file) {
        form.featured_image = file;
        imagePreview.value = URL.createObjectURL(file);
    }
};

const removeImage = () => {
    form.featured_image = null;
    imagePreview.value = null;
};

// Auto-generate slug from title
const generateSlug = () => {
    if (!isEditing.value || !props.post?.slug) {
        form.slug = form.title
            .toLowerCase()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }
};

watch(() => form.title, generateSlug);

const submit = () => {
    if (isEditing.value) {
        form.post(route('admin.posts.update', props.post.id));
    } else {
        form.post(route('admin.posts.store'));
    }
};

const toggleTag = (tagId) => {
    const index = form.tags.indexOf(tagId);
    if (index > -1) {
        form.tags.splice(index, 1);
    } else {
        form.tags.push(tagId);
    }
};
</script>

<template>
    <Head :title="isEditing ? `Editar: ${post.title}` : 'Nuevo Artículo'" />

    <AdminLayout>
        <div class="py-6">
            <!-- Header -->
            <div class="mb-6 px-4 sm:px-0">
                <Link :href="route('admin.posts.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 artículos
                </Link>
                <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
                    {{ isEditing ? 'Editar Artículo' : 'Nuevo Artículo' }}
                </h1>
            </div>

            <form @submit.prevent="submit">
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <!-- Main Content -->
                    <div class="lg:col-span-2 space-y-6">
                        <!-- Title & Slug -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6">
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Título *
                                    </label>
                                    <input
                                        v-model="form.title"
                                        type="text"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-lg"
                                        placeholder="Título del artículo"
                                        required
                                    />
                                    <p v-if="form.errors.title" class="mt-1 text-sm text-red-600">{{ form.errors.title }}</p>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        URL amigable (slug)
                                    </label>
                                    <div class="flex items-center gap-2">
                                        <span class="text-gray-500 dark:text-gray-400 text-sm">/blog/</span>
                                        <input
                                            v-model="form.slug"
                                            type="text"
                                            class="flex-1 rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white font-mono text-sm"
                                            placeholder="url-del-articulo"
                                        />
                                    </div>
                                    <p v-if="form.errors.slug" class="mt-1 text-sm text-red-600">{{ form.errors.slug }}</p>
                                </div>
                            </div>
                        </div>

                        <!-- Excerpt -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Extracto
                            </label>
                            <textarea
                                v-model="form.excerpt"
                                rows="3"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                                placeholder="Breve descripción del artículo (máx. 500 caracteres)"
                                maxlength="500"
                            ></textarea>
                            <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                                {{ form.excerpt?.length || 0 }}/500 caracteres
                            </p>
                            <p v-if="form.errors.excerpt" class="mt-1 text-sm text-red-600">{{ form.errors.excerpt }}</p>
                        </div>

                        <!-- Content -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Contenido *
                            </label>
                            <TiptapEditor 
                                v-model="form.content"
                                :upload-url="route('admin.posts.upload-image')"
                                placeholder="Escribe el contenido del artículo..."
                            />
                            <p v-if="form.errors.content" class="mt-1 text-sm text-red-600">{{ form.errors.content }}</p>
                        </div>

                        <!-- SEO -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">SEO</h3>
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Meta título
                                    </label>
                                    <input
                                        v-model="form.meta_title"
                                        type="text"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                                        placeholder="Título para motores de búsqueda (máx. 60)"
                                        maxlength="60"
                                    />
                                    <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                                        {{ form.meta_title?.length || 0 }}/60 caracteres
                                    </p>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Meta descripción
                                    </label>
                                    <textarea
                                        v-model="form.meta_description"
                                        rows="2"
                                        class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                                        placeholder="Descripción para motores de búsqueda (máx. 160)"
                                        maxlength="160"
                                    ></textarea>
                                    <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                                        {{ form.meta_description?.length || 0 }}/160 caracteres
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Sidebar -->
                    <div class="lg:col-span-1 space-y-6">
                        <!-- Publish -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Publicar</h3>
                            
                            <div class="flex items-center justify-between mb-4">
                                <span class="text-sm text-gray-700 dark:text-gray-300">Estado</span>
                                <label class="relative inline-flex items-center cursor-pointer">
                                    <input type="checkbox" v-model="form.is_published" 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_published ? 'Publicado' : 'Borrador' }}
                                    </span>
                                </label>
                            </div>

                            <button
                                type="submit"
                                :disabled="form.processing"
                                class="w-full py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
                            >
                                <span v-if="form.processing" class="flex items-center justify-center">
                                    <svg 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>
                                    Guardando...
                                </span>
                                <span v-else>
                                    {{ isEditing ? 'Actualizar' : 'Publicar' }}
                                </span>
                            </button>
                        </div>

                        <!-- Featured Image -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Imagen Destacada</h3>
                            
                            <div v-if="imagePreview" class="relative mb-4">
                                <img :src="imagePreview" class="w-full h-40 object-cover rounded-lg" />
                                <button 
                                    type="button"
                                    @click="removeImage"
                                    class="absolute top-2 right-2 p-1 bg-red-500 text-white rounded-full hover:bg-red-600"
                                >
                                    <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="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>

                            <label class="block cursor-pointer">
                                <div class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-6 text-center hover:border-blue-400 transition-colors">
                                    <svg class="mx-auto h-10 w-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                    </svg>
                                    <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
                                        Arrastra o haz clic para subir
                                    </p>
                                </div>
                                <input 
                                    type="file"
                                    accept="image/*"
                                    class="hidden"
                                    @change="handleImageChange"
                                />
                            </label>
                            <p v-if="form.errors.featured_image" class="mt-1 text-sm text-red-600">{{ form.errors.featured_image }}</p>
                        </div>

                        <!-- Category -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Categoría</h3>
                            <select
                                v-model="form.category_id"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                            >
                                <option value="">Sin categoría</option>
                                <option v-for="cat in categories" :key="cat.id" :value="cat.id">
                                    {{ cat.name }}
                                </option>
                            </select>
                            <Link 
                                :href="route('admin.categories.index')"
                                class="mt-2 inline-block text-sm text-blue-600 hover:text-blue-800 dark:text-blue-400"
                            >
                                + Gestionar categorías
                            </Link>
                        </div>

                        <!-- Tags -->
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Etiquetas</h3>
                            <div class="flex flex-wrap gap-2">
                                <button
                                    v-for="tag in tags"
                                    :key="tag.id"
                                    type="button"
                                    @click="toggleTag(tag.id)"
                                    :class="[
                                        'px-3 py-1 text-sm rounded-full transition-colors',
                                        form.tags.includes(tag.id)
                                            ? 'bg-blue-600 text-white'
                                            : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                                    ]"
                                >
                                    {{ tag.name }}
                                </button>
                            </div>
                            <div v-if="!tags?.length" class="text-sm text-gray-500 dark:text-gray-400">
                                No hay etiquetas creadas
                            </div>
                            <Link 
                                :href="route('admin.tags.index')"
                                class="mt-2 inline-block text-sm text-blue-600 hover:text-blue-800 dark:text-blue-400"
                            >
                                + Gestionar etiquetas
                            </Link>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </AdminLayout>
</template>
