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

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

/** Estado */
const billingRequests = ref([]);
const showDetailModal = ref(false);
const selectedRequest = ref(null);

/** Métodos */
const searcher = useSearcher({
    url: apiURL('clients?with=sales'),
    onSuccess: (r) => {
        billingRequests.value = r.clients || r.data || [];
    },
    onError: (error) => {
        console.error('❌ ERROR al cargar solicitudes de facturación:', error);
        billingRequests.value = [];
        window.Notify.error('Error al cargar solicitudes de facturación');
    }
});

const openDetailModal = (request) => {
    selectedRequest.value = request;
    showDetailModal.value = true;
};

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

const refreshList = () => {
    searcher.search();
};

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

<template>
    <div>
        <SearcherHead
            :title="'Solicitudes de Facturación'"
            placeholder="Buscar por folio, cliente o RFC..."
            @search="(x) => searcher.search(x)"
        >
        </SearcherHead>

        <div class="pt-2 w-full">
            <Table
                :items="billingRequests"
                @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">CLIENTE</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">RFC</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">RAZÓN SOCIAL</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">RÉGIMEN FISCAL</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">FECHA REGISTRO</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="request in items"
                        :key="request.id"
                        class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                    >
                        <td class="px-6 py-4 text-left">
                            <p class="text-sm font-medium text-gray-900 dark:text-gray-100">
                                {{ request.name }}
                            </p>
                            <p class="text-xs text-gray-500 dark:text-gray-400">
                                {{ request.email }}
                            </p>
                            <p class="text-xs text-gray-500 dark:text-gray-400">
                                {{ request.phone || 'N/A' }}
                            </p>
                        </td>
                        
                        <td class="px-6 py-4 text-left">
                            <p class="text-sm text-gray-700 dark:text-gray-300 font-mono">
                                {{ request.rfc || 'N/A' }}
                            </p>
                        </td>
                        
                        <td class="px-6 py-4 text-left">
                            <p class="text-sm text-gray-700 dark:text-gray-300">
                                {{ request.razon_social || 'N/A' }}
                            </p>
                        </td>
                        
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm text-gray-700 dark:text-gray-300">
                                {{ request.regimen_fiscal || 'N/A' }}
                            </p>
                        </td>
                        
                        <td class="px-6 py-4 text-center">
                            <p class="text-sm text-gray-700 dark:text-gray-300">
                                {{ formatDate(request.created_at) }}
                            </p>
                        </td>
                        
                        <td class="px-6 py-4 text-center">
                            <div class="flex items-center justify-center space-x-2">
                                <button
                                    @click="openDetailModal(request)"
                                    class="inline-flex items-center px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-xs font-medium rounded-md transition-colors"
                                    title="Ver detalles"
                                >
                                    <GoogleIcon name="visibility" class="text-base mr-1" />
                                    Ver
                                </button>
                            </div>
                        </td>
                    </tr>
                </template>

                <template #empty>
                    <td colspan="6" class="table-cell text-center">
                        <div class="flex flex-col items-center justify-center py-12 text-gray-500">
                            <GoogleIcon
                                name="receipt"
                                class="text-6xl mb-3 opacity-50"
                            />
                            <p class="font-semibold text-lg mb-1">
                                No hay solicitudes de facturación
                            </p>
                            <p class="text-sm text-gray-400">
                                Las solicitudes de facturación aparecerán aquí
                            </p>
                        </div>
                    </td>
                </template>
            </Table>
        </div>

        <!-- Modal de detalle -->
        <BillingRequestDetailModal
            v-if="showDetailModal"
            :request="selectedRequest"
            @close="closeDetailModal"
            @refresh="refreshList"
        />
    </div>
</template>

<style scoped>
/* Estilos adicionales si son necesarios */
</style>
