<script setup>
import { onMounted, ref } from 'vue';
import { useSearcher, apiURL } from '@Services/Api';
import returnsService from '@Services/returnsService';
import { formatCurrency, formatDate } from '@/utils/formatters';

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

/** Estado */
const models = ref([]);
const showDetailModal = ref(false);
const showCreateModal = ref(false);
const selectedReturn = ref(null);

/** Buscador de devoluciones */
const searcher = useSearcher({
    url: apiURL('returns'),
    onSuccess: (r) => {
        models.value = r.returns || r;
    },
    onError: (error) => {
        models.value = { data: [], total: 0 };
        window.Notify.error('Error al cargar devoluciones');
    }
});

/** Métodos */
const openDetailModal = async (returnItem) => {
    try {
        const response = await returnsService.getReturnDetails(returnItem.id);
        // Backend retorna: { model: {...} }
        selectedReturn.value = response.model || response;
        showDetailModal.value = true;
    } catch (error) {
        window.Notify.error('Error al cargar los detalles de la devolución');
    }
};

const closeDetailModal = () => {
    showDetailModal.value = false;
    selectedReturn.value = null;
};

const onReturnCancelled = () => {
    closeDetailModal();
    searcher.search();
};


/** Helpers de método de reembolso */
const getRefundMethodLabel = (method) => {
    const labels = {
        cash: 'Efectivo',
        credit_card: 'Credito',
        debit_card: 'Debito'
    };
    return labels[method] || method || '-';
};

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

/** Ciclo de vida */
onMounted(() => {
    searcher.search();
});
</script>

<template>
    <div>
        <SearcherHead
            title="Devoluciones"
            placeholder="Buscar por folio de venta o usuario..."
            @search="(x) => searcher.search(x)"
        >
        </SearcherHead>
        <div class="pt-2 w-full">
            <Table
                :items="models"
                :processing="searcher.processing"
                @send-pagination="(page) => searcher.pagination(page)"
            >
                <template #head>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">FOLIO</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">VENTA ORIGINAL</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-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">USUARIO</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">REEMBOLSO</th>
                    <th class="px-6 py-3 text-right 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">
                            <div class="flex items-center gap-2">
                                <span class="text-sm font-mono font-semibold text-gray-900 dark:text-gray-100">
                                    {{ model.return_number }}
                                </span>
                                <span v-if="model.deleted_at"
                                      class="px-2 py-0.5 text-xs font-semibold rounded-full bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300">
                                    Cancelada
                                </span>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm font-mono text-indigo-600 dark:text-indigo-400">
                                {{ model.sale?.invoice_number || '-' }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm text-gray-700 dark:text-gray-300">
                                {{ formatDate(model.created_at) }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm text-gray-700 dark:text-gray-300">
                                {{ model.user?.name || '-' }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <span class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium rounded-full bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300">
                                <GoogleIcon :name="getRefundMethodIcon(model.refund_method)" class="text-sm" />
                                {{ getRefundMethodLabel(model.refund_method) }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right">
                            <span class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                                {{ formatCurrency(model.total) }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <button
                                @click="openDetailModal(model)"
                                class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300 transition-colors"
                                title="Ver detalles"
                            >
                                <GoogleIcon name="visibility" class="text-xl" />
                            </button>
                        </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="sync"
                                class="text-6xl mb-2 opacity-50"
                            />
                            <p class="font-semibold">
                                No hay devoluciones registradas
                            </p>
                            <p class="text-sm mt-1">
                                Las devoluciones aparecerán aquí
                            </p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>
    </div>

    <!-- Modal de Detalle -->
    <ReturnDetailModal
        :show="showDetailModal"
        :return-data="selectedReturn"
        @close="closeDetailModal"
        @cancelled="onReturnCancelled"
    />
</template>