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

const props = defineProps({
    modelValue: {
        type: Array,
        default: () => []
    },
    disabled: {
        type: Boolean,
        default: false
    },
    allowRemove: {
        type: Boolean,
        default: true
    }
});

const emit = defineEmits(['update:modelValue']);

const inputRefs = ref([]);

const serials = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
});

const validCount = computed(() => {
    return serials.value.filter(s => s.serial_number.trim()).length;
});

const isDuplicate = (index) => {
    const val = serials.value[index]?.serial_number?.trim();
    if (!val) return false;
    return serials.value.some((s, i) => i !== index && s.serial_number.trim() === val);
};

const updateSerial = (index, value) => {
    const updated = [...serials.value];
    updated[index] = { ...updated[index], serial_number: value };
    serials.value = updated;
};

const removeSerial = (index) => {
    if (serials.value[index]?.locked) return;
    const updated = serials.value.filter((_, i) => i !== index);
    serials.value = updated;
};

const addAndFocus = async () => {
    const updated = [...serials.value, { serial_number: '', locked: false }];
    serials.value = updated;
    await nextTick();
    const lastIndex = updated.length - 1;
    inputRefs.value[lastIndex]?.focus();
};

const onKeydown = async (event, index) => {
    if (event.key === 'Enter') {
        event.preventDefault();
        const current = serials.value[index]?.serial_number?.trim();
        if (!current) return;

        // Si es el último input, agregar uno nuevo
        if (index === serials.value.length - 1) {
            await addAndFocus();
        } else {
            // Si no es el último, mover foco al siguiente
            await nextTick();
            inputRefs.value[index + 1]?.focus();
        }
    }
};

const setInputRef = (el, index) => {
    if (el) inputRefs.value[index] = el;
};

// Asegurar que siempre haya al menos un input vacío al final para escanear
watch(() => props.modelValue, (val) => {
    if (!val || val.length === 0) return;
    const lastItem = val[val.length - 1];
    // Si el último item tiene valor y no está bloqueado, agregar input vacío
    if (lastItem.serial_number.trim() && !lastItem.locked) {
        const hasEmptyUnlocked = val.some(s => !s.locked && !s.serial_number.trim());
        if (!hasEmptyUnlocked) {
            // No emitir aquí para evitar loop, se maneja con el botón/Enter
        }
    }
}, { deep: true });
</script>

<template>
    <div class="space-y-2">
        <div
            v-for="(item, index) in serials"
            :key="index"
            class="flex items-center gap-2"
        >
            <!-- Icono de estado -->
            <div class="shrink-0 w-5 flex items-center justify-center">
                <GoogleIcon
                    v-if="item.locked"
                    name="lock"
                    class="text-sm text-gray-400"
                    title="Serial vendido - no editable"
                />
                <span
                    v-else-if="isDuplicate(index)"
                    class="text-red-500 text-xs font-bold"
                    title="Serial duplicado"
                >!</span>
                <GoogleIcon
                    v-else-if="item.serial_number.trim()"
                    name="qr_code_2"
                    class="text-sm text-gray-400"
                />
                <span v-else class="text-gray-300 text-xs">{{ index + 1 }}</span>
            </div>

            <!-- Input -->
            <input
                :ref="(el) => setInputRef(el, index)"
                :value="item.serial_number"
                @input="updateSerial(index, $event.target.value)"
                @keydown="onKeydown($event, index)"
                type="text"
                :disabled="props.disabled || item.locked"
                :placeholder="item.locked ? '' : 'Escanear o escribir serial...'"
                class="flex-1 px-2.5 py-1.5 text-sm font-mono border rounded-lg transition-colors focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                :class="{
                    'bg-gray-100 dark:bg-gray-900 border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-500 cursor-not-allowed': item.locked,
                    'border-red-400 dark:border-red-600 bg-red-50 dark:bg-red-900/10': isDuplicate(index),
                    'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100': !item.locked && !isDuplicate(index),
                    'opacity-50 cursor-not-allowed': props.disabled && !item.locked
                }"
            />

            <!-- Badge estado -->
            <span
                v-if="item.locked"
                class="shrink-0 text-xs px-1.5 py-0.5 rounded"
                :class="item.lock_reason === 'traspasado'
                    ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'
                    : item.lock_reason === 'salida'
                        ? 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400'
                        : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'"
            >
                {{
                    item.lock_reason === 'traspasado' ? 'Traspasado' :
                    item.lock_reason === 'salida' ? 'Salida' :
                    'Vendido'
                }}
            </span>

            <!-- Botón eliminar -->
            <button
                v-if="!item.locked && !props.disabled && props.allowRemove"
                type="button"
                @click="removeSerial(index)"
                class="shrink-0 p-1 text-gray-400 hover:text-red-500 transition-colors"
                title="Eliminar serial"
            >
                <GoogleIcon name="close" class="text-base" />
            </button>
            <div v-else-if="!item.locked" class="shrink-0 w-7"></div>
        </div>

        <!-- Botón agregar -->
        <button
            v-if="!props.disabled && props.allowRemove"
            type="button"
            @click="addAndFocus"
            class="flex items-center gap-1.5 text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 dark:hover:text-indigo-300 transition-colors py-1"
        >
            <GoogleIcon name="add" class="text-base" />
            Agregar serial
        </button>

        <!-- Contador -->
        <div v-if="validCount > 0 && !props.disabled" class="flex items-center gap-1 text-xs text-gray-600 dark:text-gray-400">
            <GoogleIcon name="qr_code_2" class="text-sm shrink-0" />
            <span>{{ validCount }} serial(es) ingresado(s)</span>
        </div>
    </div>
</template>
