<script setup>
import { ref, computed, watch } from 'vue';
import { formatCurrency, formatDate } from '@/utils/formatters';
import { page } from '@Services/Page';

import returnsService from '@Services/returnsService';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import Modal from '@Holos/Modal.vue';
import FormInput from '@Holos/Form/Input.vue';
import useCashRegister from '@/stores/cashRegister';

/** Props */
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    sale: {
        type: Object,
        default: null
    }
});

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

/** Store */
const cashRegisterStore = useCashRegister();

/** Estado */
const loading = ref(false);
const saleData = ref(null);
const returnableItems = ref([]);
const selectedItems = ref([]);
const reason = ref('');
const reasonText = ref('');
const notes = ref('');

/** Opciones de motivo */
const reasonOptions = [
    { value: 'defective', label: 'Producto defectuoso' },
    { value: 'wrong_product', label: 'Producto incorrecto' },
    { value: 'change_of_mind', label: 'Cambio de opinión' },
    { value: 'damaged', label: 'Producto dañado' },
    { value: 'other', label: 'Otro' }
];

/** Computados */
const hasSelectedItems = computed(() => {
    return selectedItems.value.some(item => item.selected && item.quantity > 0);
});

const subtotalReturn = computed(() => {
    return selectedItems.value
        .filter(item => item.selected && item.quantity > 0)
        .reduce((total, item) => {
            return total + (parseFloat(item.unit_price) * item.quantity);
        }, 0);
});

const taxReturn = computed(() => {
    if (!saleData.value || !saleData.value.subtotal || !saleData.value.tax) {
        return 0;
    }
    // Calcular impuesto proporcional basado en la tasa de la venta original
    const taxRate = parseFloat(saleData.value.tax) / parseFloat(saleData.value.subtotal);
    return subtotalReturn.value * taxRate;
});

const totalReturn = computed(() => {
    return subtotalReturn.value + taxReturn.value;
});

const canSubmit = computed(() => {
    return hasSelectedItems.value && reason.value !== '';
});

/** Watchers */
watch(() => props.show, async (isShown) => {
    if (isShown) {
        resetForm();
        // Cargar el estado de la caja registradora
        await cashRegisterStore.loadCurrentRegister();
        if (props.sale) {
            searchSale();
        }
    }
});

/** Métodos */
const resetForm = () => {
    saleData.value = null;
    returnableItems.value = [];
    selectedItems.value = [];
    reason.value = '';
    reasonText.value = '';
    notes.value = '';
    loading.value = false;
};

const searchSale = async () => {
    if (!props.sale?.id) {
        window.Notify.error('No se proporcionó una venta válida');
        return;
    }

    loading.value = true;

    try {
        const response = await returnsService.getReturnableItems(props.sale.id);

        // Guardar datos de la venta
        saleData.value = response.sale || null;

        // Obtener items devolvibles
        const items = response.returnable_items || [];

        if (!items || items.length === 0) {
            window.Notify.warning('Esta venta no tiene items disponibles para devolución');
            loading.value = false;
            return;
        }

        returnableItems.value = items;

        // Inicializar items seleccionables con estructura del API
        selectedItems.value = items.map(item => ({
            sale_detail_id: item.sale_detail_id,
            inventory_id: item.inventory_id,
            product_name: item.product_name,
            unit_price: item.unit_price,
            quantity_sold: item.quantity_sold,
            quantity_already_returned: item.quantity_already_returned,
            quantity_returnable: item.quantity_returnable,
            available_serials: item.available_serials || [],
            // Estado de selección
            selected: false,
            quantity: 0,
            selectedSerials: []
        }));
    } catch (error) {
        console.error('Error al buscar venta:', error);
        window.Notify.error('No se encontró la venta o no está disponible para devolución');
    } finally {
        loading.value = false;
    }
};

const toggleItem = (index) => {
    const item = selectedItems.value[index];
    item.selected = !item.selected;
    
    if (item.selected) {
        // Si tiene seriales, no asignar cantidad automáticamente
        if (item.available_serials.length > 0) {
            item.quantity = 0;
            item.selectedSerials = [];
        } else {
            item.quantity = item.quantity_returnable;
        }
    } else {
        item.quantity = 0;
        item.selectedSerials = [];
    }
};

const updateQuantity = (index, value) => {
    const item = selectedItems.value[index];
    const qty = parseInt(value) || 0;
    item.quantity = Math.min(Math.max(0, qty), item.quantity_returnable);
    item.selected = item.quantity > 0;
};

const toggleSerial = (itemIndex, serial) => {
    const item = selectedItems.value[itemIndex];
    const serialIndex = item.selectedSerials.findIndex(s => s.serial_number === serial.serial_number);
    
    if (serialIndex > -1) {
        item.selectedSerials.splice(serialIndex, 1);
    } else {
        if (item.selectedSerials.length < item.quantity_returnable) {
            item.selectedSerials.push(serial);
        }
    }
    
    item.quantity = item.selectedSerials.length;
    item.selected = item.quantity > 0;
};

const isSerialSelected = (itemIndex, serial) => {
    const item = selectedItems.value[itemIndex];
    return item.selectedSerials.some(s => s.serial_number === serial.serial_number);
};

const hasSerials = (item) => {
    return item.available_serials && item.available_serials.length > 0;
};

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

const submitReturn = async () => {
    if (!canSubmit.value) {
        window.Notify.error('Selecciona al menos un item y proporciona un motivo');
        return;
    }

    // Validar que haya una caja abierta
    if (!cashRegisterStore.hasOpenRegister) {
        window.Notify.error('Debes tener una caja abierta para procesar devoluciones');
        return;
    }

    loading.value = true;

    try {
        const items = selectedItems.value
            .filter(item => item.selected && item.quantity > 0)
            .map(item => ({
                sale_detail_id: item.sale_detail_id,
                quantity_returned: item.quantity,
                serial_numbers: item.selectedSerials.map(s => s.serial_number)
            }));

        const returnData = {
            sale_id: saleData.value?.id,
            user_id: page.user.id,
            cash_register_id: cashRegisterStore.currentRegisterId || null,
            refund_method: saleData.value?.payment_method || 'cash',
            reason: reason.value,
            reason_text: reasonText.value.trim() || null,
            notes: notes.value.trim() || null,
            items: items
        };

        const response = await returnsService.createReturn(returnData);
        window.Notify.success(response.message || 'Devolución procesada exitosamente');
        emit('created');
    } catch (error) {
        console.error('Error al crear devolución:', error);
        window.Notify.error(error.message || 'Error al procesar la devolución');
    } finally {
        loading.value = false;
    }
};
</script>

<template>
    <Modal :show="show" max-width="3xl" @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="w-12 h-12 bg-indigo-100 dark:bg-indigo-900/30 rounded-xl flex items-center justify-center">
                        <GoogleIcon name="sync" class="text-2xl text-indigo-600 dark:text-indigo-400" />
                    </div>
                    <div>
                        <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                            Nueva Devolución
                        </h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">
                            Seleccionar productos a devolver
                        </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-2xl" />
                </button>
            </div>

            <!-- Seleccionar Items -->
            <div class="space-y-4">

                <!-- Info de la venta -->
                <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 mb-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-500 dark:text-gray-400">Venta seleccionada:</p>
                            <p class="text-lg font-semibold text-indigo-600 dark:text-indigo-400 font-mono">
                                {{ saleData?.invoice_number || '-' }}
                            </p>
                        </div>
                        <div class="text-right">
                            <p class="text-sm text-gray-500 dark:text-gray-400">Total de venta:</p>
                            <p class="text-lg font-semibold text-gray-900 dark:text-gray-100">
                                {{ formatCurrency(saleData?.total) }}
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Lista de items -->
                <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden max-h-64 overflow-y-auto">
                    <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                        <thead class="bg-gray-50 dark:bg-gray-800 sticky top-0">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase w-10">
                                    <span class="sr-only">Seleccionar</span>
                                </th>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
                                    Producto
                                </th>
                                <th class="px-4 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase w-32">
                                    Cantidad
                                </th>
                                <th class="px-4 py-3 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase w-28">
                                    Precio
                                </th>
                                <th class="px-4 py-3 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase w-28">
                                    Subtotal
                                </th>
                            </tr>
                        </thead>
                        <tbody class="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
                            <template v-for="(item, index) in selectedItems" :key="item.sale_detail_id">
                                <tr
                                    class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                                    :class="{ 'bg-indigo-50 dark:bg-indigo-900/20': item.selected }"
                                >
                                    <td class="px-4 py-3">
                                        <input
                                            type="checkbox"
                                            :checked="item.selected"
                                            @change="toggleItem(index)"
                                            class="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"
                                        />
                                    </td>
                                    <td class="px-4 py-3">
                                        <p class="text-sm font-medium text-gray-900 dark:text-gray-100">
                                            {{ item.product_name }}
                                            <span></span>
                                        </p>
                                        <div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
                                            <span>Vendido: {{ item.quantity_sold }}</span>
                                            <span v-if="item.quantity_already_returned > 0" class="text-orange-600 dark:text-orange-400">
                                                • Ya devuelto: {{ item.quantity_already_returned }}
                                            </span>
                                            <span class="text-green-600 dark:text-green-400">
                                                • Disponible: {{ item.quantity_returnable }}
                                            </span>
                                        </div>
                                    </td>
                                    <td class="px-4 py-3 text-center">
                                        <input
                                            v-if="!hasSerials(item)"
                                            type="number"
                                            :value="item.quantity"
                                            :max="item.quantity_returnable"
                                            :min="0"
                                            @input="updateQuantity(index, $event.target.value)"
                                            class="w-20 px-2 py-1 text-center text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-indigo-500 focus:border-indigo-500"
                                        />
                                        <span v-else class="text-sm font-medium text-gray-900 dark:text-gray-100">
                                            {{ item.quantity }} / {{ item.quantity_returnable }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 text-right">
                                        <span class="text-sm text-gray-700 dark:text-gray-300">
                                            {{ formatCurrency(item.unit_price) }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 text-right">
                                        <span class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                                            {{ formatCurrency(parseFloat(item.unit_price) * item.quantity) }}
                                        </span>
                                    </td>
                                </tr>
                                <!-- Fila de seriales si el producto tiene -->
                                <tr v-if="hasSerials(item) && item.selected">
                                    <td colspan="5" class="px-4 py-3 bg-gray-50 dark:bg-gray-800/50">
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-2">
                                            Selecciona los seriales a devolver:
                                        </p>
                                        <div class="flex flex-wrap gap-2">
                                            <button
                                                v-for="serial in item.available_serials"
                                                :key="serial.serial_number"
                                                @click="toggleSerial(index, serial)"
                                                class="px-3 py-1 text-xs font-mono rounded-lg border transition-colors"
                                                :class="isSerialSelected(index, serial)
                                                    ? 'bg-indigo-100 border-indigo-300 text-indigo-700 dark:bg-indigo-900/30 dark:border-indigo-700 dark:text-indigo-400'
                                                    : 'bg-white border-gray-300 text-gray-700 hover:border-indigo-300 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300'"
                                            >
                                                {{ serial.serial_number }}
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </div>

                <!-- Motivo y Método de Reembolso -->
                <div class="grid grid-cols-1 md:grid-cols-1 gap-4">
                    <!-- Motivo de devolución -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Motivo de devolución <span class="text-red-500">*</span>
                        </label>
                        <select
                            v-model="reason"
                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-indigo-500 focus:border-indigo-500"
                        >
                            <option value="">Selecciona un motivo</option>
                            <option v-for="opt in reasonOptions" :key="opt.value" :value="opt.value">
                                {{ opt.label }}
                            </option>
                        </select>
                    </div>
                </div>

                <!-- Descripción adicional del motivo -->
                <div v-if="reason === 'other'">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Describe el motivo
                    </label>
                    <textarea
                        v-model="reasonText"
                        rows="2"
                        placeholder="Describe el motivo de la devolución..."
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 focus:ring-indigo-500 focus:border-indigo-500 resize-none"
                    ></textarea>
                </div>

                <!-- Notas adicionales -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Notas adicionales (opcional)
                    </label>
                    <textarea
                        v-model="notes"
                        rows="2"
                        placeholder="Información adicional sobre la devolución..."
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 focus:ring-indigo-500 focus:border-indigo-500 resize-none"
                    ></textarea>
                </div>

                <!-- Desglose de totales a devolver -->
                <div class="flex justify-end">
                    <div class="bg-indigo-50 dark:bg-indigo-900/20 border border-indigo-200 dark:border-indigo-800 rounded-lg px-6 py-4 min-w-64">
                        <div class="space-y-2">
                            <div class="flex justify-between text-sm">
                                <span class="text-indigo-600 dark:text-indigo-400">Subtotal:</span>
                                <span class="text-indigo-700 dark:text-indigo-300 font-medium">
                                    {{ formatCurrency(subtotalReturn) }}
                                </span>
                            </div>
                            <div class="flex justify-between text-sm">
                                <span class="text-indigo-600 dark:text-indigo-400">IVA:</span>
                                <span class="text-indigo-700 dark:text-indigo-300 font-medium">
                                    {{ formatCurrency(taxReturn) }}
                                </span>
                            </div>
                            <div class="flex justify-between pt-2 border-t border-indigo-200 dark:border-indigo-700">
                                <span class="text-xs text-indigo-600 dark:text-indigo-400 uppercase font-semibold">Total a Devolver</span>
                                <span class="text-2xl font-bold text-indigo-700 dark:text-indigo-300">
                                    {{ formatCurrency(totalReturn) }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Footer -->
            <div class="flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
                <button
                    type="button"
                    class="px-4 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 text-sm font-semibold rounded-lg transition-colors"
                    @click="handleClose"
                >
                    Cancelar
                </button>
                <button
                    type="button"
                    :disabled="!canSubmit || loading"
                    class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-400 disabled:cursor-not-allowed text-white text-sm font-semibold rounded-lg transition-colors flex items-center gap-2"
                    @click="submitReturn"
                >
                    <GoogleIcon v-if="loading" name="sync" class="animate-spin" />
                    <GoogleIcon v-else name="check" />
                    Procesar Devolución
                </button>
            </div>
        </div>
    </Modal>
</template>