<script setup>
import { onMounted, ref, computed } from 'vue';
import { useApi, useSearcher, apiURL } from '@Services/Api';
import { formatDate, formatCurrency } 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 stats = ref({
    pending: 0,
    processed: 0,
    rejected: 0,
    total: 0,
    today_pending: 0,
    this_month: 0
});
const selectedStatus = ref('pending');
const showDetailModal = ref(false);
const selectedRequest = ref(null);
const loadingStats = ref(false);

const api = useApi();

/** Computed */
const statusOptions = [
    { value: 'all', label: 'Todas', icon: 'list', color: 'gray' },
    { value: 'pending', label: 'Pendientes', icon: 'schedule', color: 'yellow' },
    { value: 'processed', label: 'Procesadas', icon: 'check_circle', color: 'green' },
    { value: 'rejected', label: 'Rechazadas', icon: 'cancel', color: 'red' }
];

const getStatusBadge = (status) => {
    const badges = {
        pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300',
        processed: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300',
        rejected: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300'
    };
    return badges[status] || 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-300';
};

/** Métodos */
const searcher = useSearcher({
    url: apiURL('invoice-requests'),
    filters: computed(() => ({
        status: selectedStatus.value === 'all' ? undefined : selectedStatus.value
    })),
    onSuccess: (r) => {
        // El componente Table espera el objeto de paginación completo, no solo el array
        billingRequests.value = r.invoice_requests || {};
    },
    onError: (error) => {
        billingRequests.value = {};
        window.Notify.error('Error al cargar solicitudes de facturación');
    }
});

const fetchStats = () => {
    loadingStats.value = true;
    api.get(apiURL('invoice-requests/stats'), {
        onSuccess: (data) => {
            stats.value = data.stats || {};
        },
        onError: () => {
            window.Notify.error('Error al cargar estadísticas');
        },
        onFinish: () => {
            loadingStats.value = false;
        }
    });
};

const openDetailModal = async (request) => {
    // Cargar detalles completos
    api.get(apiURL(`invoice-requests/${request.id}`), {
        onSuccess: (data) => {
            selectedRequest.value = data.invoice_request;
            showDetailModal.value = true;
        },
        onError: () => {
            window.Notify.error('Error al cargar detalles de la solicitud');
        }
    });
};

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

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

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

<template>
    <div>
        <!-- Estadísticas -->
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6">
            <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Total</p>
                        <p class="text-2xl font-bold text-gray-900 dark:text-white">
                            {{ stats.total }}
                        </p>
                    </div>
                    <GoogleIcon name="receipt_long" class="text-3xl text-gray-400" />
                </div>
            </div>

            <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Pendientes</p>
                        <p class="text-2xl font-bold text-yellow-600 dark:text-yellow-400">
                            {{ stats.pending }}
                        </p>
                    </div>
                    <GoogleIcon name="schedule" class="text-3xl text-yellow-400" />
                </div>
            </div>

            <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Procesadas</p>
                        <p class="text-2xl font-bold text-green-600 dark:text-green-400">
                            {{ stats.processed }}
                        </p>
                    </div>
                    <GoogleIcon name="check_circle" class="text-3xl text-green-400" />
                </div>
            </div>

            <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Rechazadas</p>
                        <p class="text-2xl font-bold text-red-600 dark:text-red-400">
                            {{ stats.rejected }}
                        </p>
                    </div>
                    <GoogleIcon name="cancel" class="text-3xl text-red-400" />
                </div>
            </div>

            <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Hoy</p>
                        <p class="text-2xl font-bold text-blue-600 dark:text-blue-400">
                            {{ stats.today_pending }}
                        </p>
                    </div>
                    <GoogleIcon name="today" class="text-3xl text-blue-400" />
                </div>
            </div>

            <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Este mes</p>
                        <p class="text-2xl font-bold text-purple-600 dark:text-purple-400">
                            {{ stats.this_month }}
                        </p>
                    </div>
                    <GoogleIcon name="calendar_month" class="text-3xl text-purple-400" />
                </div>
            </div>
        </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">FOLIO</th>
                    <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-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">ESTADO</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">UUID CFDI</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">ARCHIVOS</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">FECHA SOLICITUD</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-mono font-semibold text-gray-900 dark:text-gray-100">
                                {{ request.sale?.invoice_number || 'N/A' }}
                            </p>
                        </td>

                        <td class="px-6 py-4 text-left">
                            <p class="text-sm font-medium text-gray-900 dark:text-gray-100">
                                {{ request.client?.name || 'N/A' }}
                            </p>
                            <p class="text-xs text-gray-500 dark:text-gray-400">
                                {{ request.client?.email || '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.client?.rfc || 'N/A' }}
                            </p>
                        </td>

                        <td class="px-6 py-4 text-right">
                            <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                                {{ formatCurrency(request.sale?.total) }}
                            </p>
                        </td>

                        <td class="px-6 py-4 text-center">
                            <span
                                :class="[
                                    'inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold',
                                    getStatusBadge(request.status)
                                ]"
                            >
                                {{ statusOptions.find(o => o.value === request.status)?.label }}
                            </span>
                        </td>

                        <!-- UUID del CFDI -->
                        <td class="px-6 py-4 text-center">
                            <div v-if="request.cfdi_uuid" class="flex flex-col items-center">
                                <p class="text-xs font-mono text-gray-700 dark:text-gray-300 break-all max-w-[200px]">
                                    {{ request.cfdi_uuid }}
                                </p>
                            </div>
                            <span v-else class="text-xs text-gray-400 dark:text-gray-500">
                                Sin UUID
                            </span>
                        </td>

                        <!-- Archivos disponibles -->
                        <td class="px-6 py-4 text-center">
                            <div class="flex items-center justify-center gap-2">
                                <!-- XML -->
                                <a
                                    v-if="request.invoice_xml_url"
                                    :href="request.invoice_xml_url"
                                    target="_blank"
                                    download
                                    class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-blue-100 hover:bg-blue-200 dark:bg-blue-900/30 dark:hover:bg-blue-900/50 transition-colors"
                                    title="Descargar XML"
                                >
                                    <GoogleIcon name="description" class="text-lg text-blue-600 dark:text-blue-400" />
                                </a>
                                <div
                                    v-else
                                    class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800"
                                    title="Sin XML"
                                >
                                    <GoogleIcon name="description" class="text-lg text-gray-400" />
                                </div>

                                <!-- PDF -->
                                <a
                                    v-if="request.invoice_pdf_url"
                                    :href="request.invoice_pdf_url"
                                    target="_blank"
                                    download
                                    class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-red-100 hover:bg-red-200 dark:bg-red-900/30 dark:hover:bg-red-900/50 transition-colors"
                                    title="Descargar PDF"
                                >
                                    <GoogleIcon name="picture_as_pdf" class="text-lg text-red-600 dark:text-red-400" />
                                </a>
                                <div
                                    v-else
                                    class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800"
                                    title="Sin PDF"
                                >
                                    <GoogleIcon name="picture_as_pdf" class="text-lg text-gray-400" />
                                </div>
                            </div>
                        </td>

                        <td class="px-6 py-4 text-center">
                            <p class="text-sm text-gray-700 dark:text-gray-300">
                                {{ formatDate(request.requested_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="9" class="table-cell text-center">
                        <div class="flex flex-col items-center justify-center py-12 text-gray-500">
                            <GoogleIcon
                                name="receipt_long"
                                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>
