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

import SearcherHead from '@Holos/Searcher.vue';
import Table from '@Holos/Table.vue';
import Modal from '@Holos/Modal.vue';
import FormInput from '@Holos/Form/Input.vue';
import FormError from '@Holos/Form/Elements/Error.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';

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

/** Estado */
const inventoryId = computed(() => route.params.id);
const inventory = ref(null);
const serials = ref({ data: [], total: 0 });
const statusFilter = ref('');

// Modales
const showCreateModal = ref(false);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const showBulkModal = ref(false);
const editingSerial = ref(null);
const deletingSerial = ref(null);

// Bulk import
const bulkSerials = ref('');
const bulkProcessing = ref(false);

/** Formularios */
const form = useForm({
    serial_number: '',
    notes: ''
});

const editForm = useForm({
    serial_number: '',
    notes: ''
});

/** 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 loadSerials = (filters = {}) => {
    searcher.load({
        url: apiURL(`inventario/${inventoryId.value}/serials`),
        filters: {
            ...filters,
            status: statusFilter.value || undefined
        }
    });
};

const onSearch = (query) => {
    searcher.search(query, { status: statusFilter.value || undefined });
};

const onStatusChange = () => {
    loadSerials({ q: searcher.query });
};

// Crear serial
const openCreateModal = () => {
    form.reset();
    showCreateModal.value = true;
};

const closeCreateModal = () => {
    showCreateModal.value = false;
    form.reset();
};

const createSerial = () => {
    const url = apiURL(`inventario/${inventoryId.value}/serials`);
    console.log('Creating serial at URL:', url, 'inventoryId:', inventoryId.value);

    form.post(url, {
        onSuccess: (response) => {
            Notify.success('Número de serie creado exitosamente');
            if (response.inventory) {
                inventory.value = response.inventory;
            }
            closeCreateModal();
            loadSerials();
        },
        onError: () => {
            Notify.error('Error al crear el número de serie');
        }
    });
};

// Editar serial
const openEditModal = (serial) => {
    editingSerial.value = serial;
    editForm.serial_number = serial.serial_number;
    editForm.notes = serial.notes || '';
    showEditModal.value = true;
};

const closeEditModal = () => {
    showEditModal.value = false;
    editingSerial.value = null;
    editForm.reset();
};

const updateSerial = () => {
    editForm.put(apiURL(`inventario/${inventoryId.value}/serials/${editingSerial.value.id}`), {
        onSuccess: () => {
            Notify.success('Número de serie actualizado');
            closeEditModal();
            loadSerials();
        },
        onError: () => {
            Notify.error('Error al actualizar el número de serie');
        }
    });
};

// Eliminar serial
const openDeleteModal = (serial) => {
    deletingSerial.value = serial;
    showDeleteModal.value = true;
};

const closeDeleteModal = () => {
    showDeleteModal.value = false;
    deletingSerial.value = null;
};

const confirmDelete = async () => {
    try {
        await serialService.deleteSerial(inventoryId.value, deletingSerial.value.id);
        Notify.success('Número de serie eliminado');
        closeDeleteModal();
        loadSerials();
    } catch (error) {
        Notify.error('Error al eliminar el número de serie');
    }
};

// Navegación
const goBack = () => {
    router.push({ name: 'pos.inventory.index' });
};

// 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">
                            | Categoría: {{ 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 y filtros -->
        <SearcherHead
            title="Números de Serie"
            placeholder="Buscar por número de serie..."
            @search="onSearch"
        >
            <!-- Filtro de estado -->
            <select
                v-model="statusFilter"
                @change="onStatusChange"
                class="px-3 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"
            >
                <option value="">Todos los estados</option>
                <option value="disponible">Disponible</option>
                <option value="vendido">Vendido</option>
            </select>
            <button
                class="flex items-center gap-2 px-3 py-2 bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-semibold rounded-lg transition-colors shadow-sm"
                @click="openCreateModal"
            >
                <GoogleIcon name="add" class="text-xl" />
                Agregar Serial
            </button>
        </SearcherHead>

        <!-- Tabla de seriales -->
        <div class="pt-2 w-full">
            <Table
                :items="serials"
                :processing="searcher.processing"
                @send-pagination="(page) => searcher.pagination(page, { status: statusFilter || undefined })"
            >
                <template #head>
                    <th class="px-6 py-3 text-left 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 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="serial in items"
                        :key="serial.id"
                        class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                    >
                        <td class="px-6 py-4 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 class="px-6 py-4 whitespace-nowrap text-center">
                            <div class="flex items-center justify-center gap-2">
                                <button
                                    v-if="serial.status === 'disponible'"
                                    @click="openEditModal(serial)"
                                    class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300 transition-colors"
                                    title="Editar serial"
                                >
                                    <GoogleIcon name="edit" class="text-xl" />
                                </button>
                                <button
                                    v-if="serial.status === 'disponible'"
                                    @click="openDeleteModal(serial)"
                                    class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300 transition-colors"
                                    title="Eliminar serial"
                                >
                                    <GoogleIcon name="delete" class="text-xl" />
                                </button>
                                <span
                                    v-if="serial.status === 'vendido'"
                                    class="text-gray-400 text-xs"
                                    title="No se puede editar/eliminar un serial vendido"
                                >
                                    Venta {{ serial.sale_detail?.sale?.invoice_number || `#${serial.sale_detail_id}` }}
                                </span>
                            </div>
                        </td>
                    </tr>
                </template>
                <template #empty>
                    <td colspan="5" class="table-cell text-center">
                        <div class="flex flex-col items-center justify-center py-8 text-gray-500">
                            <GoogleIcon
                                name="qr_code_2"
                                class="text-6xl mb-2 opacity-50"
                            />
                            <p class="font-semibold">
                                No hay números de serie registrados
                            </p>
                            <p class="text-sm mt-1">
                                Agrega seriales individuales o importa múltiples
                            </p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>

        <!-- Modal Crear Serial -->
        <Modal :show="showCreateModal" max-width="sm" @close="closeCreateModal">
            <div class="p-6">
                <div class="flex items-center justify-between mb-6">
                    <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                        Agregar Número de Serie
                    </h3>
                    <button
                        @click="closeCreateModal"
                        class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                        <GoogleIcon name="close" class="text-xl" />
                    </button>
                </div>

                <form @submit.prevent="createSerial" class="space-y-4">
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            NÚMERO DE SERIE *
                        </label>
                        <FormInput
                            v-model="form.serial_number"
                            type="text"
                            placeholder="Ej: ABC123456789"
                            required
                        />
                        <FormError :message="form.errors?.serial_number" />
                    </div>

                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            NOTAS (OPCIONAL)
                        </label>
                        <textarea
                            v-model="form.notes"
                            class="w-full px-3 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"
                            rows="2"
                            placeholder="Notas adicionales..."
                        ></textarea>
                        <FormError :message="form.errors?.notes" />
                    </div>

                    <div class="flex items-center justify-end gap-3 pt-4">
                        <button
                            type="button"
                            @click="closeCreateModal"
                            class="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"
                        >
                            Cancelar
                        </button>
                        <button
                            type="submit"
                            :disabled="form.processing"
                            class="px-4 py-2 text-sm font-semibold text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        >
                            <span v-if="form.processing">Guardando...</span>
                            <span v-else>Guardar</span>
                        </button>
                    </div>
                </form>
            </div>
        </Modal>

        <!-- Modal Editar Serial -->
        <Modal :show="showEditModal" max-width="sm" @close="closeEditModal">
            <div class="p-6">
                <div class="flex items-center justify-between mb-6">
                    <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                        Editar Número de Serie
                    </h3>
                    <button
                        @click="closeEditModal"
                        class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                        <GoogleIcon name="close" class="text-xl" />
                    </button>
                </div>

                <form @submit.prevent="updateSerial" class="space-y-4">
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            NÚMERO DE SERIE *
                        </label>
                        <FormInput
                            v-model="editForm.serial_number"
                            type="text"
                            placeholder="Ej: ABC123456789"
                            required
                        />
                        <FormError :message="editForm.errors?.serial_number" />
                    </div>

                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            NOTAS (OPCIONAL)
                        </label>
                        <textarea
                            v-model="editForm.notes"
                            class="w-full px-3 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"
                            rows="2"
                            placeholder="Notas adicionales..."
                        ></textarea>
                        <FormError :message="editForm.errors?.notes" />
                    </div>

                    <div class="flex items-center justify-end gap-3 pt-4">
                        <button
                            type="button"
                            @click="closeEditModal"
                            class="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"
                        >
                            Cancelar
                        </button>
                        <button
                            type="submit"
                            :disabled="editForm.processing"
                            class="px-4 py-2 text-sm font-semibold text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        >
                            <span v-if="editForm.processing">Actualizando...</span>
                            <span v-else>Actualizar</span>
                        </button>
                    </div>
                </form>
            </div>
        </Modal>

        <!-- Modal Eliminar Serial -->
        <Modal :show="showDeleteModal" max-width="sm" @close="closeDeleteModal">
            <div class="p-6">
                <div class="flex items-center justify-between mb-6">
                    <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                        Eliminar Número de Serie
                    </h3>
                    <button
                        @click="closeDeleteModal"
                        class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                        <GoogleIcon name="close" class="text-xl" />
                    </button>
                </div>

                <div class="mb-6">
                    <p class="text-gray-600 dark:text-gray-400">
                        ¿Estás seguro de eliminar el número de serie
                        <span class="font-mono font-bold text-gray-900 dark:text-gray-100">
                            {{ deletingSerial?.serial_number }}
                        </span>?
                    </p>
                    <p class="text-sm text-red-600 mt-2">
                        Esta acción no se puede deshacer y reducirá el stock del producto.
                    </p>
                </div>

                <div class="flex items-center justify-end gap-3">
                    <button
                        @click="closeDeleteModal"
                        class="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"
                    >
                        Cancelar
                    </button>
                    <button
                        @click="confirmDelete"
                        class="px-4 py-2 text-sm font-semibold text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors"
                    >
                        Eliminar
                    </button>
                </div>
            </div>
        </Modal>
    </div>
</template>
