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

/** Props */
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    product: {
        type: Object,
        required: true
    },
    excludeSerials: {
        type: Array,
        default: () => []
    },
    warehouseId: {
        type: Number,
        default: null
    },
    mainWarehouse: {
        type: Boolean,
        default: false
    },
    preSelectedSerials: {
        type: Array,
        default: () => []
    }
});

/** Emits */
const emit = defineEmits(['close', 'confirm']);

/** Estado */
const loading = ref(false);
const availableSerials = ref([]);
const selectedSerials = ref([]);
const searchQuery = ref('');

/** Computados */
const filteredSerials = computed(() => {
    if (!searchQuery.value) {
        return availableSerials.value;
    }
    const query = searchQuery.value.toLowerCase();
    return availableSerials.value.filter(serial =>
        serial.serial_number.toLowerCase().includes(query)
    );
});

const selectedCount = computed(() => selectedSerials.value.length);

const hasEnoughStock = computed(() => {
    return availableSerials.value.length > 0;
});

const canConfirm = computed(() => {
    return selectedSerials.value.length > 0;
});

/** Métodos */
const loadSerials = async () => {
    loading.value = true;
    try {
        const response = await serialService.getAvailableSerials(props.product.id, props.warehouseId, { mainWarehouse: props.mainWarehouse });
        const fetched = (response.serials?.data || []).filter(
            serial => !props.excludeSerials.includes(serial.serial_number)
        );
        const fetchedIds = new Set(fetched.map(s => s.id));
        const extras = props.preSelectedSerials.filter(s => !fetchedIds.has(s.id));
        availableSerials.value = [...extras, ...fetched];

        selectedSerials.value = props.preSelectedSerials.filter(s =>
            availableSerials.value.some(a => a.id === s.id)
        );
    } catch (error) {
        console.error('Error loading serials:', error);
        availableSerials.value = [];
    } finally {
        loading.value = false;
    }
};

const toggleSerial = (serial) => {
    const index = selectedSerials.value.findIndex(s => s.id === serial.id);
    if (index > -1) {
        selectedSerials.value.splice(index, 1);
    } else {
        selectedSerials.value.push(serial);
    }
};

const isSelected = (serial) => {
    return selectedSerials.value.some(s => s.id === serial.id);
};

const selectAll = () => {
    selectedSerials.value = [...availableSerials.value];
};

const clearSelection = () => {
    selectedSerials.value = [];
};

const handleConfirm = () => {
    emit('confirm', {
        serials: selectedSerials.value,
        serialNumbers: selectedSerials.value.map(s => s.serial_number),
        quantity: selectedSerials.value.length
    });
};

const handleClose = () => {
    emit('close');
};

const resetState = () => {
    selectedSerials.value = [];
    searchQuery.value = '';
};

/** Watchers */
watch(() => props.show, (isShown) => {
    if (isShown) {
        resetState();
        loadSerials();
    }
},{ immediate: true });
</script>

<template>
    <Modal :show="show" max-width="lg" @close="handleClose">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center justify-between mb-6">
                <div class="flex items-center gap-3">
                    <div class="flex items-center justify-center w-12 h-12 rounded-full bg-emerald-100 dark:bg-emerald-900/30">
                        <GoogleIcon name="qr_code_2" class="text-2xl text-emerald-600 dark:text-emerald-400" />
                    </div>
                    <div>
                        <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                            Seleccionar Números de Serie
                        </h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">
                            {{ product.name }}
                        </p>
                    </div>
                </div>
                <button
                    @click="handleClose"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                >
                    <GoogleIcon name="close" class="text-xl" />
                </button>
            </div>

            <!-- Loading -->
            <div v-if="loading" class="flex items-center justify-center py-12">
                <GoogleIcon name="hourglass_empty" class="text-4xl text-gray-400 animate-spin" />
            </div>

            <!-- Sin seriales disponibles -->
            <div v-else-if="!hasEnoughStock" class="text-center py-8">
                <GoogleIcon name="error" class="text-5xl text-red-400 mb-3" />
                <p class="text-lg font-semibold text-gray-900 dark:text-gray-100">
                    Stock insuficiente
                </p>
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-2">
                    Solo hay {{ availableSerials.length }} serial(es) disponible(s), pero necesitas {{ quantity }}.
                </p>
                <button
                    @click="handleClose"
                    class="mt-4 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                    Cerrar
                </button>
            </div>

            <!-- Content -->
            <div v-else class="space-y-6">

                <!-- Selección manual -->
                <div class="space-y-4">
                    <!-- Buscador y acciones -->
                    <div class="flex items-center gap-3">
                        <div class="flex-1 relative">
                            <GoogleIcon
                                name="search"
                                class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
                            />
                            <input
                                v-model="searchQuery"
                                type="text"
                                placeholder="Buscar número de serie..."
                                class="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-100"
                            />
                        </div>
                        <button
                            v-if="selectedCount < availableSerials.length"
                            @click="selectAll"
                            class="px-3 py-2 text-xs font-medium text-indigo-600 bg-indigo-50 rounded-lg hover:bg-indigo-100 transition-colors"
                        >
                            Seleccionar todos
                        </button>
                        <button
                            v-if="selectedCount > 0"
                            @click="clearSelection"
                            class="px-3 py-2 text-xs font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
                        >
                            Limpiar
                        </button>
                    </div>

                    <!-- Contador -->
                    <div class="flex items-center justify-between text-sm">
                        <span class="text-gray-600 dark:text-gray-400">
                            {{ availableSerials.length }} serial(es) disponible(s)
                        </span>
                        <span
                            class="font-semibold"
                            :class="{
                                'text-green-600': selectedCount > 0,
                                'text-gray-500': selectedCount === 0
                            }"
                        >
                            {{ selectedCount }} seleccionado(s)
                        </span>
                    </div>

                    <!-- Lista de seriales -->
                    <div class="max-h-64 overflow-y-auto border border-gray-200 dark:border-gray-700 rounded-lg divide-y divide-gray-100 dark:divide-gray-700">
                        <button
                            v-for="serial in filteredSerials"
                            :key="serial.id"
                            type="button"
                            class="w-full flex items-center gap-3 p-3 text-left transition-colors"
                            :class="{
                                'bg-indigo-50 dark:bg-indigo-900/20': isSelected(serial),
                                'hover:bg-gray-50 dark:hover:bg-gray-800': !isSelected(serial)
                            }"
                            @click="toggleSerial(serial)"
                        >
                            <div
                                class="w-5 h-5 rounded border-2 flex items-center justify-center transition-colors"
                                :class="{
                                    'border-indigo-500 bg-indigo-500': isSelected(serial),
                                    'border-gray-300 dark:border-gray-600': !isSelected(serial)
                                }"
                            >
                                <GoogleIcon
                                    v-if="isSelected(serial)"
                                    name="check"
                                    class="text-xs text-white"
                                />
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-mono font-semibold text-gray-900 dark:text-gray-100">
                                    {{ serial.serial_number }}
                                </p>
                                <p v-if="serial.notes" class="text-xs text-gray-500 dark:text-gray-400 truncate">
                                    {{ serial.notes }}
                                </p>
                            </div>
                        </button>

                        <!-- Sin resultados -->
                        <div v-if="filteredSerials.length === 0" class="p-8 text-center text-gray-500">
                            <GoogleIcon name="search_off" class="text-3xl mb-2" />
                            <p class="text-sm">No se encontraron seriales</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Footer -->
            <div v-if="hasEnoughStock && !loading" class="flex items-center justify-end gap-3 mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
                <button
                    type="button"
                    @click="handleClose"
                    class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                >
                    Cancelar
                </button>
                <button
                    type="button"
                    @click="handleConfirm"
                    :disabled="!canConfirm"
                    class="flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-semibold rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                    <GoogleIcon name="check" class="text-lg" />
                    Confirmar
                </button>
            </div>
        </div>
    </Modal>
</template>
