<script setup>
import { ref, watch } from 'vue';
import { useApi, apiURL } from '@Services/Api';
import reportService from '@Services/reportService';

import Modal from '@Holos/Modal.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';

/** Eventos */
const emit = defineEmits(['close']);

/** Propiedades */
const props = defineProps({
    show: Boolean
});

/** Estado */
const api = useApi();
const warehouses = ref([]);
const isExporting = ref(false);

const form = ref({
    inventory_id: '',
    fecha_inicio: '',
    fecha_fin: '',
    warehouse_id: '',
    movement_type: '',
});

// Búsqueda de producto
let debounceTimer = null;
const productSearch = ref('');
const productSuggestions = ref([]);
const selectedProduct = ref(null);
const showSuggestions = ref(false);

/** Tipos de movimiento */
const movementTypes = [
    { value: '', label: 'Todos' },
    { value: 'entry', label: 'Entrada' },
    { value: 'exit', label: 'Salida' },
    { value: 'transfer', label: 'Traspaso' },
/*     { value: 'sale', label: 'Venta' },
    { value: 'return', label: 'Devolución' }, */
];

/** Métodos */
const loadWarehouses = () => {
    api.get(apiURL('almacenes'), {
        onSuccess: (data) => {
            warehouses.value = data.warehouses?.data || data.data || [];
        }
    });
};

const searchProduct = () => {
    const q = productSearch.value.trim();
    if (q.length < 2) {
        productSuggestions.value = [];
        showSuggestions.value = false;
        return;
    }
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
        api.get(apiURL(`inventario?q=${encodeURIComponent(q)}`), {
            onSuccess: (data) => {
                productSuggestions.value = data.products?.data || data.data || data.products || [];
                showSuggestions.value = productSuggestions.value.length > 0;
            }
        });
    }, 300);
};

const selectProduct = (product) => {
    selectedProduct.value = product;
    form.value.inventory_id = product.id;
    productSearch.value = `${product.name} (${product.sku})`;
    showSuggestions.value = false;
};

const clearProduct = () => {
    selectedProduct.value = null;
    form.value.inventory_id = '';
    productSearch.value = '';
    productSuggestions.value = [];
};

const exportKardex = async () => {
    try {
        isExporting.value = true;

        const filters = {
            fecha_inicio: form.value.fecha_inicio,
            fecha_fin: form.value.fecha_fin,
        };

        if (form.value.inventory_id) {
            filters.inventory_id = form.value.inventory_id;
        }

        if (form.value.warehouse_id) {
            filters.warehouse_id = form.value.warehouse_id;
        }

        if (form.value.movement_type) {
            filters.movement_type = form.value.movement_type;
        }

        await reportService.exportKardexToExcel(filters);
        Notify.success('Kardex exportado exitosamente');
        emit('close');
    } catch (error) {
        if (error.message) {
            Notify.error(error.message);
        } else {
            Notify.error('Error al exportar el kardex');
        }
    } finally {
        isExporting.value = false;
    }
};

const resetForm = () => {
    form.value = { inventory_id: '', fecha_inicio: '', fecha_fin: '', warehouse_id: '', movement_type: '' };
    productSearch.value = '';
    selectedProduct.value = null;
    productSuggestions.value = [];
    showSuggestions.value = false;
};

/** Observadores */
watch(() => props.show, (val) => {
    if (val) {
        resetForm();
        loadWarehouses();
    }
});
</script>

<template>
    <Modal :show="show" max-width="lg" @close="emit('close')">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center justify-between mb-5">
                <div class="flex items-center gap-2">
                    <GoogleIcon name="assignment" class="text-2xl text-emerald-600" />
                    <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">Exportar reporte</h3>
                </div>
                <button @click="emit('close')" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                    <GoogleIcon name="close" class="text-xl" />
                </button>
            </div>

            <div class="space-y-4">
                <!-- Producto -->
                <div class="relative">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Producto <span class="text-gray-400 text-xs normal-nums">(Opcional)</span></label>
                    <div class="relative">
                        <input
                            v-model="productSearch"
                            @input="searchProduct"
                            @focus="showSuggestions = productSuggestions.length > 0"
                            type="text"
                            placeholder="Buscar producto por nombre o SKU..."
                            class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500"
                            :class="{ 'pr-8': selectedProduct }"
                        />
                        <button
                            v-if="selectedProduct"
                            @click="clearProduct"
                            class="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-red-500"
                        >
                            <GoogleIcon name="close" class="text-base" />
                        </button>
                    </div>
                    <div v-if="selectedProduct" class="mt-1 text-xs text-green-600 dark:text-green-400">
                        Seleccionado: {{ selectedProduct.name }} ({{ selectedProduct.sku }})
                    </div>
                    <!-- Sugerencias -->
                    <div
                        v-if="showSuggestions"
                        class="absolute z-10 w-full mt-1 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg shadow-lg max-h-48 overflow-y-auto"
                    >
                        <button
                            v-for="product in productSuggestions"
                            :key="product.id"
                            @click="selectProduct(product)"
                            class="w-full text-left px-3 py-2 hover:bg-gray-100 dark:hover:bg-gray-600 text-sm"
                        >
                            <p class="font-medium text-gray-900 dark:text-gray-100">{{ product.name }}</p>
                            <p class="text-xs text-gray-500 dark:text-gray-400">SKU: {{ product.sku }}</p>
                        </button>
                    </div>
                </div>

                <!-- Fechas (requeridas) -->
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Desde *</label>
                        <input
                            v-model="form.fecha_inicio"
                            type="date"
                            class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500"
                        />
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Hasta *</label>
                        <input
                            v-model="form.fecha_fin"
                            type="date"
                            class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500"
                        />
                    </div>
                </div>

                <!-- Almacén (opcional) -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Almacén (opcional)</label>
                    <select
                        v-model="form.warehouse_id"
                        class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500"
                    >
                        <option value="">Todos los almacenes</option>
                        <option v-for="wh in warehouses" :key="wh.id" :value="wh.id">{{ wh.name }}</option>
                    </select>
                </div>

                <!-- Tipo de movimiento (opcional) -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Tipo de movimiento (opcional)</label>
                    <select
                        v-model="form.movement_type"
                        class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500"
                    >
                        <option v-for="type in movementTypes" :key="type.value" :value="type.value">{{ type.label }}</option>
                    </select>
                </div>
            </div>

            <!-- Botones -->
            <div class="flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
                <button
                    @click="emit('close')"
                    class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
                >
                    Cancelar
                </button>
                <button
                    @click="exportKardex"
                    :disabled="!form.fecha_inicio || !form.fecha_fin || isExporting"
                    class="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-white bg-emerald-600 hover:bg-emerald-700 rounded-lg transition-colors shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    <GoogleIcon :name="isExporting ? 'hourglass_empty' : 'download'" class="text-lg" />
                    {{ isExporting ? 'Exportando...' : 'Exportar Kardex' }}
                </button>
            </div>
        </div>
    </Modal>
</template>
