<script setup>
import { computed } from 'vue';
import { formatCurrency, formatDate } from '@/utils/formatters';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import Modal from '@Holos/Modal.vue';
import returnsService from '@Services/returnsService';

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

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

/** Computados */
const returnItems = computed(() => {
    const items = props.returnData?.details || [];
    return items;
});

const hasItems = computed(() => {
    return returnItems.value.length > 0;
});

const formattedTotal = computed(() => {
    return formatCurrency(props.returnData?.total || 0);
});

const formattedSubtotal = computed(() => {
    return formatCurrency(props.returnData?.subtotal || 0);
});

const formattedTax = computed(() => {
    return formatCurrency(props.returnData?.tax || 0);
});

const formattedDate = computed(() => {
    if (!props.returnData?.created_at) return '-';
    return formatDate(props.returnData.created_at);
});

/** Helpers de estado */
const getRefundMethodBadge = (method) => {
    const badges = {
        cash: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300',
        card: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300',
        store_credit: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300'
    };
    return badges[method] || 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300';
};

const getRefundMethodLabel = (method) => {
    const labels = {
        cash: 'Efectivo',
        credit_card: 'Credito',
        debit_card: 'Debito'
    };
    return labels[method] || method || '-';
};

const getRefundMethodIcon = (method) => {
    const icons = {
        cash: 'payments',
        credit_card: 'credit_card',
        debit_card: 'credit_card'
    };
    return icons[method] || 'payment';
};

const getReasonLabel = (reason) => {
    const labels = {
        defective: 'Producto defectuoso',
        wrong_product: 'Producto incorrecto',
        change_of_mind: 'Cambio de opinión',
        damaged: 'Producto dañado',
        other: 'Otro'
    };
    return labels[reason] || reason || '-';
};

/** Métodos */
const handleClose = () => {
    emit('close');
};

</script>

<template>
    <Modal :show="show" max-width="2xl" @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">
                            {{ returnData?.return_number || `Devolución #${returnData?.id}` }}
                        </h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">
                            {{ formattedDate }}
                        </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>

            <!-- Información General -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <!-- Venta Original -->
                <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase mb-1">Venta Original</p>
                    <p class="text-lg font-semibold text-indigo-600 dark:text-indigo-400 font-mono">
                        {{ returnData?.sale?.invoice_number || `#${returnData?.sale_id}` }}
                    </p>
                </div>

                <div v-if="returnData?.deleted_at" class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                    <span class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300">
                        <GoogleIcon name="cancel" class="text-sm" />
                        Cancelada
                    </span>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">
                        {{ formatDate(returnData.deleted_at) }}
                    </p>
                </div>

                <!-- Usuario -->
                <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase mb-1">Procesado por</p>
                    <p class="text-lg font-semibold text-gray-900 dark:text-gray-100">
                        {{ returnData?.user?.name || '-' }}
                    </p>
                </div>

                <!-- Método de Reembolso -->
                <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase mb-1">Método de Reembolso</p>
                    <span
                        class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-semibold rounded-full"
                        :class="getRefundMethodBadge(returnData?.refund_method)"
                    >
                        <GoogleIcon :name="getRefundMethodIcon(returnData?.refund_method)" class="text-sm" />
                        {{ getRefundMethodLabel(returnData?.refund_method) }}
                    </span>
                </div>
            </div>

            <!-- Motivo de devolución -->
            <div v-if="returnData?.reason || returnData?.reason_text" class="mb-6">
                <p class="text-xs text-gray-500 dark:text-gray-400 uppercase mb-2">Motivo de Devolución</p>
                <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
                    <p class="text-sm font-semibold text-yellow-800 dark:text-yellow-300 mb-1">
                        {{ getReasonLabel(returnData?.reason) }}
                    </p>
                    <p v-if="returnData?.reason_text" class="text-sm text-yellow-700 dark:text-yellow-400">
                        {{ returnData.reason_text }}
                    </p>
                </div>
            </div>

            <!-- Notas adicionales -->
            <div v-if="returnData?.notes" class="mb-6">
                <p class="text-xs text-gray-500 dark:text-gray-400 uppercase mb-2">Notas</p>
                <div class="bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                    <p class="text-sm text-gray-700 dark:text-gray-300">
                        {{ returnData.notes }}
                    </p>
                </div>
            </div>

            <!-- Items Devueltos -->
            <div class="mb-6">
                <p class="text-xs text-gray-500 dark:text-gray-400 uppercase mb-3">
                    Productos Devueltos ({{ returnItems.length }})
                </p>

                <div v-if="hasItems" class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
                    <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                        <thead class="bg-gray-50 dark:bg-gray-800">
                            <tr>
                                <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">
                                    Cantidad
                                </th>
                                <th class="px-4 py-3 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
                                    Precio Unit.
                                </th>
                                <th class="px-4 py-3 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
                                    Subtotal
                                </th>
                            </tr>
                        </thead>
                        <tbody class="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
                            <tr v-for="item in returnItems" :key="item.id">
                                <td class="px-4 py-3">
                                    <div>
                                        <p class="text-sm font-medium text-gray-900 dark:text-gray-100">
                                            {{ item.product_name || item.inventory?.name || 'Producto' }}
                                        </p>
                                        <p v-if="item.inventory?.sku" class="text-xs text-gray-500 dark:text-gray-400">
                                            SKU: {{ item.inventory.sku }}
                                        </p>
                                        <!-- Seriales devueltos -->
                                        <div v-if="item.serials && item.serials.length > 0" class="mt-1">
                                            <p class="text-xs text-gray-500 dark:text-gray-400">Seriales:</p>
                                            <div class="flex flex-wrap gap-1 mt-1">
                                                <span
                                                    v-for="serial in item.serials"
                                                    :key="serial.id || serial.serial_number"
                                                    class="inline-flex px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded font-mono"
                                                >
                                                    {{ serial.serial_number }}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 py-3 text-center">
                                    <span class="text-sm font-medium text-gray-900 dark:text-gray-100">
                                        {{ item.quantity_returned || item.quantity }}
                                    </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(item.subtotal) }}
                                    </span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div v-else class="text-center py-8 text-gray-500 dark:text-gray-400">
                    <GoogleIcon name="inventory_2" class="text-4xl mb-2 opacity-50" />
                    <p>No hay items en esta devolución</p>
                </div>
            </div>

            <!-- Totales -->
            <div class="border-t border-gray-200 dark:border-gray-700 pt-4">
                <div class="flex justify-end">
                    <div class="w-64 space-y-2">
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600 dark:text-gray-400">Subtotal:</span>
                            <span class="text-gray-900 dark:text-gray-100">{{ formattedSubtotal }}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600 dark:text-gray-400">IVA:</span>
                            <span class="text-gray-900 dark:text-gray-100">{{ formattedTax }}</span>
                        </div>
                        <div class="flex justify-between pt-2 border-t border-gray-200 dark:border-gray-700">
                            <span class="text-base font-semibold text-gray-900 dark:text-gray-100">Total Devuelto:</span>
                            <span class="text-xl font-bold text-indigo-600 dark:text-indigo-400">{{ formattedTotal }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Footer -->
            <div class="flex justify-between items-center mt-6">
                <div></div>
                <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"
                >
                    Cerrar
                </button>
            </div>
        </div>
    </Modal>
</template>