<script setup>
import { onMounted, ref, computed } from 'vue';
import { formatCurrency } from '@/utils/formatters';
import { useRoute, useRouter } from 'vue-router';
import { useSearcher, apiURL } from '@Services/Api';

const route = useRoute();
const router = useRouter();

import SearcherHead from '@Holos/Searcher.vue';
import Table from '@Holos/Table.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';

/** Estado */
const warehouseId = computed(() => route.params.id);
const warehouse = ref(null);
const warehouses = ref([]);
const models = ref([]);
const categories = ref([]);
const selectedCategory = ref('');
const currentSearch = ref('');

/** Métodos */
const searcher = useSearcher({
    url: apiURL(`inventario/almacen/${warehouseId.value}`),
    onSuccess: (r) => {

        // Procesar productos
        let productsArray = [];
        if (r.products && Array.isArray(r.products)) {
            productsArray = r.products;
        } else if (r.data?.products && Array.isArray(r.data.products)) {
            productsArray = r.data.products;
        }

        models.value = {
            data: productsArray,
            total: productsArray.length
        };

        // Obtener warehouse desde la lista de almacenes cargados
        const whId = r.warehouse_id || r.data?.warehouse_id;
        if (whId && warehouses.value.length > 0) {
            warehouse.value = warehouses.value.find(w => w.id === whId) || null;
        }

    },
    onError: (error) => {
        console.error('❌ Error al cargar:', error);
        models.value = { data: [], total: 0 };
    }
});

const loadCategories = async () => {
    try {
        const response = await fetch(apiURL('categorias'), {
            headers: {
                'Authorization': `Bearer ${sessionStorage.token}`,
                'Accept': 'application/json'
            }
        });
        const result = await response.json();
        if (result.data && result.data.categories && result.data.categories.data) {
            categories.value = result.data.categories.data;
        }
    } catch (error) {
        console.error('Error al cargar clasificaciones:', error);
    }
};

const loadWarehouses = async () => {
    try {
        const response = await fetch(apiURL('almacenes'), {
            headers: {
                'Authorization': `Bearer ${sessionStorage.token}`,
                'Accept': 'application/json'
            }
        });
        const result = await response.json();
        if (result.data && result.data.warehouses && result.data.warehouses.data) {
            warehouses.value = result.data.warehouses.data;
        } else if (result.data && Array.isArray(result.data)) {
            warehouses.value = result.data;
        }
    } catch (error) {
        console.error('Error al cargar almacenes:', error);
    }
};

const applyFilters = () => {
    const filters = {
        category_id: selectedCategory.value || '',
    };

    searcher.search('', filters);
};

const handleCategoryChange = () => {
    applyFilters();
};

const goBack = () => {
    router.push({ name: 'pos.warehouses.index' });
};

const openSerials = (product) => {
    router.push({
        name: 'pos.inventory.serials',
        params: { id: product.id },
        query: {
            warehouse_id: warehouseId.value,
            is_main: warehouse.value?.is_main ? '1' : '0'
        }
    });
};

/** Ciclos */
onMounted(async () => {
    await Promise.all([
        loadWarehouses(),
        loadCategories()
    ]);
    applyFilters();
});
</script>

<template>
    <div>
        <!-- Header con navegación -->
        <div class="mb-4">
            <button
                @click="goBack"
                class="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100 transition-colors"
            >
                <GoogleIcon name="arrow_back" class="text-xl" />
                Volver a Almacenes
            </button>
        </div>

        <!-- Info del almacén -->
        <div v-if="warehouse" class="mb-6 p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                        {{ warehouse.name }}
                    </h2>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                        Código: {{ warehouse.code }}
                        <span v-if="warehouse.is_main" class="ml-2 px-2 py-0.5 text-xs font-semibold rounded bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-300">
                            Principal
                        </span>
                    </p>
                </div>
                <div class="text-right">
                    <p class="text-sm text-gray-500 dark:text-gray-400">Productos</p>
                    <p class="text-2xl font-bold text-indigo-600 dark:text-indigo-400">
                        {{ models.total || 0 }}
                    </p>
                </div>
            </div>
        </div>

        <SearcherHead
            title="Inventario del Almacén"
            placeholder="Buscar por nombre, SKU o código de barras..."
            @search="(x) => {
                currentSearch = x;
                const filters = { category_id: selectedCategory || '' };
                searcher.search(x, filters);
            }"
        >
        </SearcherHead>

        <!-- Filtros -->
        <div class="pt-4 pb-2">
            <div class="flex items-end gap-4">
                <div>
                    <label class="text-sm font-medium text-gray-700 dark:text-gray-300">Filtrar por clasificación:</label>
                    <select
                        v-model="selectedCategory"
                        @change="handleCategoryChange"
                        class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"
                    >
                        <option value="">Todas las clasificaciones</option>
                        <option v-for="category in categories" :key="category.id" :value="category.id">
                            {{ category.name }}
                        </option>
                    </select>
                </div>
                <div>
                    <button
                        @click="selectedCategory = ''; currentSearch = ''; applyFilters();"
                        class="px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors bg-gray-100 dark:bg-gray-700 rounded-lg"
                    >
                        Limpiar filtros
                    </button>
                </div>
            </div>
        </div>

        <div class="pt-6 w-full">
            <Table
                :items="models"
                :processing="searcher.processing"
                @send-pagination="(page) => searcher.pagination(page)"
            >
                <template #head>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">SKU / CÓDIGO</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">PRODUCTO</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">CLASIFICACIÓN</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">PRECIO</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">STOCK</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">TOTAL</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">ACCIONES</th>
                </template>
                <template #body="{items}">
                    <tr
                        v-for="model in items"
                        :key="model.id"
                        class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                    >
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <span class="text-sm font-mono text-gray-600 dark:text-gray-400">{{ model.sku }}</span>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <div>
                                <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{{ model.name }}</p>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <span class="text-sm text-gray-700 dark:text-gray-300">
                                {{ model.category?.name || '-' }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <div class="text-sm">
                                <p class="font-semibold text-gray-900 dark:text-gray-100">
                                    {{ formatCurrency(model.price?.retail_price) }}
                                </p>
                                <p class="text-xs text-gray-500 dark:text-gray-400">
                                    Costo: {{ formatCurrency(model.price?.cost) }}
                                </p>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <span
                                class="font-bold text-base"
                                :class="{
                                    'text-red-500': model.warehouse_stock < 10,
                                    'text-green-600': model.warehouse_stock >= 10
                                }"
                            >
                                {{ model.warehouse_stock }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <div class="text-sm">
                                <p class="font-semibold text-gray-900 dark:text-gray-100">
                                    {{ formatCurrency((model.price?.cost || 0) * (model.warehouse_stock || 0)) }}
                                </p>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <div class="flex items-center justify-center gap-2">
                                <button
                                    v-if="!model.unit_of_measure?.allows_decimals"
                                    @click="openSerials(model)"
                                    class="text-emerald-600 hover:text-emerald-900 dark:text-emerald-400 dark:hover:text-emerald-300 transition-colors"
                                    title="Gestionar números de serie"
                                >
                                    <GoogleIcon name="qr_code_2" class="text-xl" />
                                </button>
                                <span
                                    v-else
                                    class="text-gray-400 dark:text-gray-600 cursor-not-allowed"
                                    :title="`No disponible: ${model.unit_of_measure.name} (${model.unit_of_measure.abbreviation}) permite decimales`"
                                >
                                    <GoogleIcon name="qr_code_2" class="text-xl opacity-30" />
                                </span>
                            </div>
                        </td>
                    </tr>
                </template>
                <template #empty>
                    <td colspan="7" class="table-cell text-center">
                        <div class="flex flex-col items-center justify-center py-8 text-gray-500">
                            <GoogleIcon
                                name="inventory_2"
                                class="text-6xl mb-2 opacity-50"
                            />
                            <p class="font-semibold">
                                No hay productos con stock en este almacén
                            </p>
                            <p class="text-sm mt-2">
                                Los productos aparecerán aquí cuando tengan stock mayor a 0
                            </p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>
    </div>
</template>
