<div x-data="modals" @keydown.escape="closeModal" class="bg-white rounded-lg shadow">

    <div class="container mx-auto p-6 w-full">
        <h1 class="text-2xl font-bold mb-4">PQRs</h1>
        <div class="justify-between w-full md:flex">
            <p class="mb-4 text-sm">Relación de PQRs.</p>
        </div>

        <!-- GIF de carga -->
        <div x-show="loading" class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-50 justify-center items-center">
            <img src="../img/loading.gif" alt="Cargando..." class="w-16 h-16" />
        </div>

        <!-- Mostrar registros obtenidos -->
        <div x-show="!loading && records.length > 0" class="overflow-x-auto mt-4">
            <div class="grid grid-cols-2 gap-4">
                <template x-for="(record, index) in records" :key="index">
                    <table class="min-w-full border-collapse border border-gray-200 rounded-lg overflow-hidden shadow-sm bg-gray-100 text-sm">
                        <tbody>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">No. Solicitud</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.No_Solicitud"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Fecha</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="formatDate(record.Fecha)"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Hora</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="formatTime(record.Hora)"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Clase</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.Clase.trim() || '-'"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Causal</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.Causal.trim() || '-'"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Detalle</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.Detalle.trim() || '-'"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Factura</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.Factura.trim() || '-'"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Estado</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.Estado.trim() || '-'"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Observación</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.Observacion.trim() || '-'"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Fecha Solución</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="formatDate(record.Fecha_Sol)"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Hora Solución</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="formatTime(record.Hora_Sol)"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Solución</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.Solucion.trim() || '-'"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Detalle Solución</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.DetalleSol.trim() || '-'"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Lectura</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.Lectura.trim() || '-'"></td>
                            </tr>
                            <tr>
                                <td class="border border-gray-300 px-4 py-2 text-left font-bold">Observaciones Sol</td>
                                <td class="border border-gray-300 px-4 py-2 text-left" x-text="record.Observaciones_Sol.trim() || '-'"></td>
                            </tr>
                        </tbody>
                    </table>
                </template>
            </div>           

        </div>

        <!-- Mensaje si no hay registros -->
        <div x-show="!loading && records.length === 0" class="text-center mt-4 text-gray-500">
            No se encontraron registros.
        </div>
    </div>

    <!-- Alpine.js Script -->
    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('modals', () => ({
                usuario: '{{ .user.NombreUsuario }}',
                records: [],
                loading: false,

                init() {
                    console.log('init llamado');
                    this.loadRegister();
                },

                async loadRegister() {
                    try {
                        console.log('loadRegister llamado');
                        this.loading = true;
                        const response = await fetch(`/app/loadpqrsicom/${this.usuario}`, {
                            method: 'GET',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                        });

                        if (!response.ok) {
                            throw new Error(`Error al cargar registros: ${response.statusText}`);
                        }

                        const data = await response.json();
                        console.log('Registros obtenidos:', data);
                        this.records = data?.data || [];
                    } catch (error) {
                        console.error('Error al cargar los registros:', error);
                        this.records = [];
                    } finally {
                        this.loading = false;
                    }
                },

                formatDate(date) {
                    return new Date(date).toLocaleDateString('es-CO', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit'
                    });
                },

                formatTime(time) {
                    const [hour, minute] = time.slice(11, 16).split(':');
                    return `${hour}:${minute}`;
                },

                closeModal() {
                    this.loading = false;
                },
            }));
        });
    </script>
</div>