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

const props = defineProps({
    selectedElement: {
        type: Object,
        default: null
    },
    visible: {
        type: Boolean,
        default: false
    },
    activeTextElement: {
        type: Object,
        default: null
    }
});

const emit = defineEmits(['update', 'smart-align']);

// Determinar si hay un elemento de texto activo (puede ser texto directo o celda de tabla)
const hasActiveText = computed(() => {
    return props.visible && (
        props.selectedElement?.type === 'text' || 
        props.activeTextElement?.type === 'text' ||
        (props.selectedElement?.type === 'table' && props.activeTextElement)
    );
});

// Obtener formato del elemento activo
const formatting = computed(() => {
    if (props.activeTextElement) {
        return props.activeTextElement.formatting || {};
    }
    if (props.selectedElement?.type === 'text') {
        return props.selectedElement.formatting || {};
    }
    return {};
});

// Obtener información del elemento activo
const activeElementInfo = computed(() => {
    if (props.activeTextElement) {
        return {
            type: 'text',
            context: props.selectedElement?.type === 'table' ? 'table-cell' : 'text-element'
        };
    }
    if (props.selectedElement?.type === 'text') {
        return {
            type: 'text',
            context: 'text-element'
        };
    }
    return null;
});

/** Métodos de formato */
const toggleBold = () => {
    if (!hasActiveText.value) return;
    updateFormatting('bold', !formatting.value.bold);
};

const toggleItalic = () => {
    if (!hasActiveText.value) return;
    updateFormatting('italic', !formatting.value.italic);
};

const toggleUnderline = () => {
    if (!hasActiveText.value) return;
    updateFormatting('underline', !formatting.value.underline);
};

const updateFontSize = (size) => {
    if (!hasActiveText.value) return;
    updateFormatting('fontSize', size);
};

const updateTextAlign = (align) => {
    if (!hasActiveText.value) return;
    updateFormatting('textAlign', align);
};

const updateColor = (color) => {
    if (!hasActiveText.value) return;
    updateFormatting('color', color);
};

const updateFormatting = (key, value) => {
    const newFormatting = { ...formatting.value, [key]: value };
    
    // Determinar qué elemento actualizar
    let targetId = null;
    if (props.activeTextElement) {
        targetId = props.activeTextElement.id;
    } else if (props.selectedElement?.type === 'text') {
        targetId = props.selectedElement.id;
    }
    
    if (targetId) {
        emit('update', {
            id: targetId,
            formatting: newFormatting,
            context: activeElementInfo.value?.context
        });
    }
};

/** Colores y tamaños predefinidos */
const predefinedColors = [
    '#000000', '#333333', '#666666', '#999999',
    '#FF0000', '#00FF00', '#0000FF', '#FFFF00',
    '#FF00FF', '#00FFFF', '#FFA500', '#800080'
];

const fontSizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
</script>

<template>
    <div 
        class="bg-gray-50 border-b border-gray-200 transition-all duration-300"
        :class="{
            'h-12 opacity-100': visible && hasActiveText,
            'h-0 opacity-0 overflow-hidden': !visible || !hasActiveText
        }"
    >
        <div 
            v-if="hasActiveText"
            class="flex items-center gap-4 px-4 py-2 h-full"
        >
            <!-- Información del elemento activo -->
            <div class="flex items-center gap-2 text-xs text-gray-600 border-r border-gray-300 pr-4">
                <GoogleIcon 
                    :name="activeElementInfo?.context === 'table-cell' ? 'table_chart' : 'text_fields'" 
                    class="text-sm" 
                />
                <span>
                    {{ activeElementInfo?.context === 'table-cell' ? 'Celda de tabla' : 'Texto' }}
                </span>
            </div>

            <!-- Controles de estilo -->
            <div class="flex items-center gap-1">
                <button
                    @click="toggleBold"
                    :class="[
                        'w-8 h-8 rounded flex items-center justify-center text-sm font-bold transition-colors',
                        formatting.bold
                            ? 'bg-blue-500 text-white shadow-sm'
                            : 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
                    ]"
                    title="Negrita (Ctrl+B)"
                >
                    B
                </button>
                
                <button
                    @click="toggleItalic"
                    :class="[
                        'w-8 h-8 rounded flex items-center justify-center text-sm italic transition-colors',
                        formatting.italic
                            ? 'bg-blue-500 text-white shadow-sm'
                            : 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
                    ]"
                    title="Cursiva (Ctrl+I)"
                >
                    I
                </button>
                
                <button
                    @click="toggleUnderline"
                    :class="[
                        'w-8 h-8 rounded flex items-center justify-center text-sm underline transition-colors',
                        formatting.underline
                            ? 'bg-blue-500 text-white shadow-sm'
                            : 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
                    ]"
                    title="Subrayado (Ctrl+U)"
                >
                    U
                </button>
            </div>

            <!-- Separador -->
            <div class="w-px h-6 bg-gray-300"></div>

            <!-- Tamaño de fuente -->
            <select
                :value="formatting.fontSize || 12"
                @change="updateFontSize(parseInt($event.target.value))"
                class="px-2 py-1 text-sm border border-gray-200 rounded bg-white focus:ring-2 focus:ring-blue-500"
            >
                <option v-for="size in fontSizes" :key="size" :value="size">
                    {{ size }}px
                </option>
            </select>

            <!-- Separador -->
            <div class="w-px h-6 bg-gray-300"></div>

            <!-- Alineación -->
            <div class="flex gap-1">
                <button
                    @click="updateTextAlign('left')"
                    :class="[
                        'w-8 h-8 rounded flex items-center justify-center transition-colors',
                        (formatting.textAlign || 'left') === 'left'
                            ? 'bg-blue-500 text-white shadow-sm'
                            : 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
                    ]"
                    title="Alinear izquierda"
                >
                    <GoogleIcon name="format_align_left" class="text-sm" />
                </button>
                
                <button
                    @click="updateTextAlign('center')"
                    :class="[
                        'w-8 h-8 rounded flex items-center justify-center transition-colors',
                        formatting.textAlign === 'center'
                            ? 'bg-blue-500 text-white shadow-sm'
                            : 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
                    ]"
                    title="Centrar"
                >
                    <GoogleIcon name="format_align_center" class="text-sm" />
                </button>
                
                <button
                    @click="updateTextAlign('right')"
                    :class="[
                        'w-8 h-8 rounded flex items-center justify-center transition-colors',
                        formatting.textAlign === 'right'
                            ? 'bg-blue-500 text-white shadow-sm'
                            : 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
                    ]"
                    title="Alinear derecha"
                >
                    <GoogleIcon name="format_align_right" class="text-sm" />
                </button>
            </div>

            <!-- Separador -->
            <div class="w-px h-6 bg-gray-300"></div>

            <!-- Color -->
            <div class="flex items-center gap-2">
                <div 
                    class="w-8 h-8 rounded border-2 border-gray-300 cursor-pointer relative overflow-hidden"
                    :style="{ backgroundColor: formatting.color || '#000000' }"
                    title="Color de texto"
                >
                    <input
                        type="color"
                        :value="formatting.color || '#000000'"
                        @input="updateColor($event.target.value)"
                        class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                    />
                </div>
                
                <div class="flex gap-1">
                    <button
                        v-for="color in predefinedColors.slice(0, 4)"
                        :key="color"
                        @click="updateColor(color)"
                        class="w-6 h-6 rounded border border-gray-300 hover:scale-110 transition-transform"
                        :class="{
                            'ring-2 ring-blue-500': (formatting.color || '#000000') === color
                        }"
                        :style="{ backgroundColor: color }"
                        :title="color"
                    ></button>
                </div>
            </div>

            <!-- Información de estado -->
            <div class="ml-auto text-xs text-gray-500">
                {{ activeElementInfo?.context === 'table-cell' ? 'Formateando celda de tabla' : 'Formateando texto' }}
            </div>
        </div>
    </div>
</template>