<script setup>
import { ref, computed, nextTick } from 'vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';

/** Propiedades */
const props = defineProps({
    pages: {
        type: Array,
        default: () => [{ id: 1, elements: [] }]
    },
    selectedElementId: String,
    isExporting: Boolean
});

/** Eventos */
const emit = defineEmits(['drop', 'dragover', 'click', 'add-page', 'delete-page', 'page-change']);

/** Referencias */
const viewportRef = ref(null);
const currentPage = ref(1);

/** Constantes de diseño */
const PAGE_WIDTH = 794; // A4 width in pixels (210mm @ 96dpi * 3.78)
const PAGE_HEIGHT = 1123; // A4 height in pixels (297mm @ 96dpi * 3.78)
const PAGE_MARGIN = 40;
const ZOOM_LEVEL = 0.8; // Factor de escala para visualización

/** Propiedades computadas */
const scaledPageWidth = computed(() => PAGE_WIDTH * ZOOM_LEVEL);
const scaledPageHeight = computed(() => PAGE_HEIGHT * ZOOM_LEVEL);
const totalPages = computed(() => props.pages.length);

/** Métodos */
const handleDrop = (event, pageIndex) => {
    event.preventDefault();
    
    const pageElement = event.currentTarget;
    const rect = pageElement.getBoundingClientRect();
    
    // Calcular posición relativa a la página específica
    const relativeX = (event.clientX - rect.left) / ZOOM_LEVEL;
    const relativeY = (event.clientY - rect.top) / ZOOM_LEVEL;
    
    emit('drop', {
        originalEvent: event,
        pageIndex,
        x: Math.max(PAGE_MARGIN, Math.min(PAGE_WIDTH - PAGE_MARGIN, relativeX)),
        y: Math.max(PAGE_MARGIN, Math.min(PAGE_HEIGHT - PAGE_MARGIN, relativeY))
    });
};

const handleDragOver = (event) => {
    event.preventDefault();
    emit('dragover', event);
};

const handleClick = (event, pageIndex) => {
    if (event.target.classList.contains('pdf-page')) {
        emit('click', { originalEvent: event, pageIndex });
    }
};

const addPage = () => {
    emit('add-page');
    nextTick(() => {
        scrollToPage(totalPages.value);
    });
};

const deletePage = (pageIndex) => {
    if (totalPages.value > 1) {
        emit('delete-page', pageIndex);
    }
};

const scrollToPage = (pageNumber) => {
    if (viewportRef.value) {
        const pageElement = viewportRef.value.querySelector(`[data-page="${pageNumber}"]`);
        if (pageElement) {
            pageElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    }
};

const setCurrentPage = (pageNumber) => {
    currentPage.value = pageNumber;
    emit('page-change', pageNumber);
};

/** Métodos expuestos */
defineExpose({
    scrollToPage,
    setCurrentPage,
    PAGE_WIDTH,
    PAGE_HEIGHT,
    ZOOM_LEVEL
});
</script>

<template>
    <div class="flex-1 flex flex-col bg-gray-100 dark:bg-primary-d/20">
        <!-- Toolbar de páginas -->
        <div class="flex items-center justify-between px-4 py-2 bg-white dark:bg-primary-d border-b border-gray-200 dark:border-primary/20">
            <div class="flex items-center gap-3">
                <span class="text-sm text-gray-600 dark:text-primary-dt">
                    Página {{ currentPage }} de {{ totalPages }}
                </span>
                
                <div class="flex items-center gap-1">
                    <button
                        @click="setCurrentPage(Math.max(1, currentPage - 1))"
                        :disabled="currentPage <= 1"
                        class="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed dark:text-primary-dt/70 dark:hover:text-primary-dt"
                    >
                        <GoogleIcon name="keyboard_arrow_left" class="text-lg" />
                    </button>
                    
                    <button
                        @click="setCurrentPage(Math.min(totalPages, currentPage + 1))"
                        :disabled="currentPage >= totalPages"
                        class="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed dark:text-primary-dt/70 dark:hover:text-primary-dt"
                    >
                        <GoogleIcon name="keyboard_arrow_right" class="text-lg" />
                    </button>
                </div>
            </div>

            <div class="flex items-center gap-2">
                
                <button
                    @click="addPage"
                    :disabled="isExporting"
                    class="flex items-center gap-1 px-2 py-1 text-xs bg-blue-600 hover:bg-blue-700 text-white rounded transition-colors disabled:opacity-50"
                >
                    <GoogleIcon name="add" class="text-sm" />
                    Nueva Página
                </button>
            </div>
        </div>

        <!-- Viewport de páginas -->
        <div
            ref="viewportRef"
            class="flex-1 overflow-auto p-8"
            style="background: linear-gradient(45deg, #f0f0f0 25%, transparent 25%), linear-gradient(-45deg, #f0f0f0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #f0f0f0 75%), linear-gradient(-45deg, transparent 75%, #f0f0f0 75%); background-size: 20px 20px; background-position: 0 0, 0 10px, 10px -10px, -10px 0px;"
        >
            <div class="flex flex-col items-center gap-8">
                <!-- Páginas -->
                <div
                    v-for="(page, pageIndex) in pages"
                    :key="page.id"
                    :data-page="pageIndex + 1"
                    class="relative"
                    @mouseenter="setCurrentPage(pageIndex + 1)"
                >
                    <!-- Número de página -->
                    <div class="absolute -top-6 left-0 flex items-center gap-2 text-xs text-gray-500 dark:text-primary-dt/70">
                        <span>Página {{ pageIndex + 1 }}</span>
                        
                        <button
                            v-if="totalPages > 1"
                            @click="deletePage(pageIndex)"
                            :disabled="isExporting"
                            class="text-red-500 hover:text-red-700 disabled:opacity-50"
                            title="Eliminar página"
                        >
                            <GoogleIcon name="delete" class="text-sm" />
                        </button>
                    </div>
                    
                    <!-- Página PDF -->
                    <div
                        class="pdf-page relative bg-white rounded-lg shadow-lg border border-gray-300 dark:border-primary/20"
                        :class="{
                            'ring-2 ring-blue-500': currentPage === pageIndex + 1,
                            'opacity-50': isExporting
                        }"
                        :style="{
                            width: `${scaledPageWidth}px`,
                            height: `${scaledPageHeight}px`,
                            transform: `scale(${ZOOM_LEVEL})`,
                            transformOrigin: 'top left'
                        }"
                        @drop="(e) => handleDrop(e, pageIndex)"
                        @dragover="handleDragOver"
                        @click="(e) => handleClick(e, pageIndex)"
                    >
                        <!-- Márgenes visuales -->
                        <div
                            class="absolute border border-dashed border-gray-300 dark:border-primary/30 pointer-events-none"
                            :style="{
                                top: `${PAGE_MARGIN}px`,
                                left: `${PAGE_MARGIN}px`,
                                width: `${PAGE_WIDTH - (PAGE_MARGIN * 2)}px`,
                                height: `${PAGE_HEIGHT - (PAGE_MARGIN * 2)}px`
                            }"
                        ></div>
                        
                        <!-- Elementos de la página -->
                        <slot
                            name="elements"
                            :page="page"
                            :pageIndex="pageIndex"
                            :pageWidth="PAGE_WIDTH"
                            :pageHeight="PAGE_HEIGHT"
                        />
                        
                        <!-- Indicador de página vacía -->
                        <div
                            v-if="page.elements.length === 0"
                            class="absolute inset-0 flex items-center justify-center pointer-events-none"
                        >
                            <div class="text-center text-gray-400 dark:text-primary-dt/50">
                                <GoogleIcon name="description" class="text-4xl mb-2" />
                                <p class="text-sm">Página {{ pageIndex + 1 }}</p>
                                <p class="text-xs">Arrastra elementos aquí</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Regla inferior (tamaño de referencia) -->
                    <div class="mt-2 text-xs text-gray-400 dark:text-primary-dt/50 text-center">
                        210 × 297 mm (A4)
                    </div>
                </div>
                
                <!-- Botón para agregar página al final -->
                <button
                    @click="addPage"
                    :disabled="isExporting"
                    class="flex flex-col items-center justify-center w-40 h-20 border-2 border-dashed border-gray-300 dark:border-primary/30 rounded-lg hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors disabled:opacity-50"
                >
                    <GoogleIcon name="add" class="text-2xl text-gray-400 dark:text-primary-dt/50" />
                    <span class="text-xs text-gray-500 dark:text-primary-dt/70 mt-1">Nueva Página</span>
                </button>
            </div>
        </div>

        <!-- Overlay durante exportación -->
        <div
            v-if="isExporting"
            class="absolute inset-0 bg-white/80 dark:bg-primary-d/80 flex items-center justify-center z-50"
        >
            <div class="text-center">
                <GoogleIcon name="picture_as_pdf" class="text-4xl text-red-600 dark:text-red-400 animate-pulse mb-2" />
                <p class="text-sm font-medium text-gray-900 dark:text-primary-dt">Generando PDF...</p>
                <p class="text-xs text-gray-500 dark:text-primary-dt/70">Procesando {{ totalPages }} página{{ totalPages !== 1 ? 's' : '' }}</p>
            </div>
        </div>
    </div>
</template>

<style scoped>
.pdf-page {
    transition: all 0.2s ease;
}

.pdf-page:hover {
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}
</style>