<script setup>
import { onMounted, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useSearcher, apiURL } from '@Services/Api';
import SearcherHead from '@Holos/Searcher.vue';
import Table from '@Holos/Table.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';

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

/** Estado */
const inventoryId = computed(() => route.params.id);
const warehouseId = computed(() => route.query.warehouse_id || null);
const isMainWarehouse = computed(() => !warehouseId.value || route.query.is_main === '1');
const inventory = ref(null);
const serials = ref({ data: [], total: 0 });
const activeTab = ref('disponible');

/** Buscador */
const searcher = useSearcher({
    url: apiURL(`inventario/${route.params.id}/serials`),
    filters: {},
    onSuccess: (r) => {
        serials.value = r.serials || { data: [], total: 0 };
        inventory.value = r.inventory || null;
    },
    onError: () => {
        serials.value = { data: [], total: 0 };
    }
});

/** Métodos */
const warehouseFilters = () => {
    if (!warehouseId.value) return {};
    if (route.query.is_main === '1') return { main_warehouse: 1 };
    return { warehouse_id: warehouseId.value };
};

const loadSerials = (filters = {}) => {
    searcher.load({
        url: apiURL(`inventario/${inventoryId.value}/serials`),
        filters: {
            ...warehouseFilters(),
            ...filters,
            status: activeTab.value
        }
    });
};

const onSearch = (query) => {
    searcher.search(query, { ...warehouseFilters(), status: activeTab.value });
};

const switchTab = (tab) => {
    activeTab.value = tab;
    loadSerials({ q: searcher.query });
};

// Navegación
const goBack = () => {
    router.go(-1);
};

// Badge de estado
const getStatusBadge = (status) => {
    if (status === 'disponible') {
        return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300';
    }
    return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300';
};

const getStatusLabel = (status) => {
    return status === 'disponible' ? 'Disponible' : 'Vendido';
};

/** Ciclos */
onMounted(() => {
    loadSerials();
});
</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 Inventario
            </button>
        </div>

        <!-- Info del producto -->
        <div v-if="inventory" 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">
                        {{ inventory.name }}
                    </h2>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                        SKU: {{ inventory.sku }}
                        <span v-if="inventory.category">
                            | Clasificación: {{ inventory.category.name }}
                        </span>
                    </p>
                </div>
                <div class="text-right">
                    <p class="text-2xl font-bold text-indigo-600 dark:text-indigo-400">
                        {{ inventory.stock }}
                    </p>
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">
                        Disponibles
                    </p>
                </div>
            </div>
        </div>

        <!-- Buscador -->
        <SearcherHead
            title="Números de Serie"
            placeholder="Buscar por número de serie..."
            @search="onSearch"
        />

        <!-- Pestañas -->
        <div class="mt-4 border-b border-gray-200 dark:border-gray-700">
            <nav class="-mb-px flex space-x-8" aria-label="Tabs">
                <button
                    @click="switchTab('disponible')"
                    :class="[
                        activeTab === 'disponible'
                            ? 'border-indigo-500 text-indigo-600 dark:text-indigo-400'
                            : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300',
                        'group inline-flex items-center py-4 px-1 border-b-2 font-medium text-sm transition-colors'
                    ]"
                >
                    <GoogleIcon
                        name="check_circle"
                        :class="[
                            activeTab === 'disponible' ? 'text-indigo-500 dark:text-indigo-400' : 'text-gray-400 group-hover:text-gray-500',
                            'mr-2 text-xl'
                        ]"
                    />
                    Disponibles
                </button>
                <button
                    v-if="isMainWarehouse"
                    @click="switchTab('vendido')"
                    :class="[
                        activeTab === 'vendido'
                            ? 'border-indigo-500 text-indigo-600 dark:text-indigo-400'
                            : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300',
                        'group inline-flex items-center py-4 px-1 border-b-2 font-medium text-sm transition-colors'
                    ]"
                >
                    <GoogleIcon
                        name="shopping_cart"
                        :class="[
                            activeTab === 'vendido' ? 'text-indigo-500 dark:text-indigo-400' : 'text-gray-400 group-hover:text-gray-500',
                            'mr-2 text-xl'
                        ]"
                    />
                    Vendidos
                </button>
            </nav>
        </div>

        <!-- Tabla de seriales -->
        <div class="pt-2 w-full">
            <Table
                :items="serials"
                :processing="searcher.processing"
                @send-pagination="(page) => searcher.pagination(page, { status: activeTab })"
            >
                <template #head>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">NÚMERO DE SERIE</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">ESTADO</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">NOTAS</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">FECHA</th>
                    <th v-if="activeTab === 'vendido'" class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">VENTA</th>
                </template>
                <template #body="{items}">
                    <tr
                        v-for="serial in items"
                        :key="serial.id"
                        class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                    >
                        <td class="px-6 py-4 text-center whitespace-nowrap">
                            <span class="text-sm font-mono font-semibold text-gray-900 dark:text-gray-100">
                                {{ serial.serial_number }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <span
                                class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                                :class="getStatusBadge(serial.status)"
                            >
                                {{ getStatusLabel(serial.status) }}
                            </span>
                        </td>
                        <td class="px-6 py-4">
                            <span class="text-sm text-gray-600 dark:text-gray-400">
                                {{ serial.notes || '-' }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm text-gray-500 dark:text-gray-400">
                                {{ new Date(serial.created_at).toLocaleDateString('es-MX') }}
                            </span>
                        </td>
                        <td v-if="activeTab === 'vendido'" class="px-6 py-4 whitespace-nowrap text-center">
                            <span class="text-gray-500 dark:text-gray-400 text-xs">
                                {{ serial.sale_detail?.sale?.invoice_number || `#${serial.sale_detail_id}` }}
                            </span>
                        </td>
                    </tr>
                </template>
                <template #empty>
                    <td :colspan="activeTab === 'vendido' ? 5 : 4" class="table-cell text-center">
                        <div class="flex flex-col items-center justify-center py-8 text-gray-500">
                            <GoogleIcon
                                :name="activeTab === 'disponible' ? 'qr_code_2' : 'shopping_cart'"
                                class="text-6xl mb-2 opacity-50"
                            />
                            <p class="font-semibold">
                                {{ activeTab === 'disponible' ? 'No hay seriales disponibles' : 'No hay seriales vendidos' }}
                            </p>
                            <p class="text-sm mt-1">
                                {{ activeTab === 'disponible' ? 'Agrega seriales para comenzar' : 'Los seriales vendidos aparecerán aquí' }}
                            </p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>

    </div>
</template>
