import React, { useState, useRef, useEffect } from 'react';
import { Head, router } from '@inertiajs/react';
import Layout from '../../../../Layouts';
import { Container, Row, Col, Card, Button, Table, Alert, Modal } from 'react-bootstrap';
import { useLoading } from '../../../../LoadingContext';
import styles from '../Clientes/CargaMasiva.module.css';
import { ChevronLeft, ChevronRight, Download, CheckCircle, XCircle, AlertCircle, FileSpreadsheet } from 'lucide-react';
import Swal from 'sweetalert2';
import axios from 'axios';

let xlsxPromise: Promise<typeof import('xlsx')> | null = null;
const loadXlsx = () => (xlsxPromise ??= import('xlsx'));

interface CargaGlobalAudaxProps {
    titulo: string;
}

interface ExcelRow {
    [key: string]: any;
}

interface ResultadoCarga {
    total: number;
    exitosos: number;
    creados: number;
    actualizados: number;
    omitidos: number;
    errores: number;
    detalles_errores: Array<{
        fila: number;
        error: string;
        datos: any[];
    }>;
}

interface ErrorValidacion {
    fila: number;
    errores: string[];
}

const CargaGlobalAudax: React.FC<CargaGlobalAudaxProps> = ({ titulo }) => {
    const { showLoading, hideLoading } = useLoading();
    const [isDragging, setIsDragging] = useState(false);
    const [archivo, setArchivo] = useState<File | null>(null);
    const [datosExcel, setDatosExcel] = useState<ExcelRow[]>([]);
    const [columnas, setColumnas] = useState<string[]>([]);
    const [columnasOriginales, setColumnasOriginales] = useState<string[]>([]);
    const [error, setError] = useState<string>('');
    const [resultado, setResultado] = useState<ResultadoCarga | null>(null);
    const [listErrors, setListErrors] = useState<boolean>(false);
    const [erroresValidacion, setErroresValidacion] = useState<ErrorValidacion[]>([]);
    const [showModal, setShowModal] = useState<boolean>(false);
    const [erroresFilaSeleccionada, setErroresFilaSeleccionada] = useState<ErrorValidacion | null>(null);
    const fileInputRef = useRef<HTMLInputElement>(null);
    const tableContainerRef = useRef<HTMLDivElement>(null);
    const tableErrorsRef = useRef<HTMLDivElement>(null);

    // Asegurar que el token CSRF esté disponible al montar el componente
    useEffect(() => {
        // Los interceptores globales se encargan de actualizar el token automáticamente
        // Solo verificamos que el token esté disponible en el meta tag
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
        if (csrfToken && window.axios) {
            window.axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken;
        }
    }, []);

    const toTitleCase = (str: string): string => {
        return str
            .toLowerCase()
            .split(/[\s_-]+/)
            .map(word => word.charAt(0).toUpperCase() + word.slice(1))
            .join(' ');
    };

    const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragging(true);
    };

    const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragging(false);
    };

    const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragging(false);

        const files = e.dataTransfer.files;
        if (files && files.length > 0) {
            handleFile(files[0]);
        }
    };

    const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = e.target.files;
        if (files && files.length > 0) {
            handleFile(files[0]);
        }
    };

    const handleFile = (file: File) => {
        const validTypes = [
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'text/csv'
        ];

        if (!validTypes.includes(file.type) && !file.name.match(/\.(xlsx|xls|csv)$/)) {
            setError('Por favor, selecciona un archivo Excel válido (.xlsx, .xls, .csv)');
            return;
        }

        if (file.size > 10 * 1024 * 1024) {
            setError('El archivo es demasiado grande. Tamaño máximo: 10MB');
            return;
        }

        setError('');
        setArchivo(file);
        leerExcel(file);
    };

    const leerExcel = (file: File) => {
        showLoading('Leyendo archivo Excel...');

        const reader = new FileReader();
        reader.onload = async (e) => {
            try {
                const XLSX = await loadXlsx();
                const data = e.target?.result;
                const workbook = XLSX.read(data, { type: 'binary' });

                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];

                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }) as any[][];

                if (jsonData.length > 0) {
                    const headersOriginales = jsonData[0] as string[];
                    setColumnasOriginales(headersOriginales);

                    const headersTitleCase = headersOriginales.map(header => toTitleCase(String(header)));
                    setColumnas(headersTitleCase);

                    const rows = jsonData.slice(1).map((row) => {
                        const obj: ExcelRow = {};
                        headersOriginales.forEach((header, index) => {
                            obj[header] = row[index];
                        });
                        return obj;
                    });

                    setDatosExcel(rows);
                }

                hideLoading();
            } catch (err) {
                console.error('Error al leer Excel:', err);
                setError('Error al leer el archivo Excel');
                hideLoading();
            }
        };

        reader.onerror = () => {
            setError('Error al leer el archivo');
            hideLoading();
        };

        reader.readAsBinaryString(file);
    };

    const handleProcesar = async () => {
        if (!archivo) {
            setError('Por favor, selecciona un archivo primero');
            return;
        }

        const confirmacion = await Swal.fire({
            title: '¿Procesar carga masiva?',
            text: `Se procesarán ${datosExcel.length} registros`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Sí, procesar',
            cancelButtonText: 'Cancelar',
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33'
        });

        if (!confirmacion.isConfirmed) {
            return;
        }

        try {
            showLoading('Procesando Carga Global Audax...');

            // VALIDAR: Obtener y validar el token CSRF ANTES de enviar
            // Actualizar los headers globales de axios

            const formData = new FormData();
            formData.append('archivo', archivo as File);

            // Usar window.axios - los interceptores globales validarán y agregarán el token CSRF automáticamente
            const response = await axios.post(
                route('configuracion.carga-masiva.global-audax'),
                formData,
                {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    }
                }
            );

            hideLoading();

            if (response.data.success) {
                setResultado(response.data.message);

                const { exitosos, errores, omitidos, total, creados, actualizados } = response.data;
                await Swal.fire({
                    icon: errores > 0 ? 'warning' : 'success',
                    title: 'Archivo enviado correctamente.',
                    text: response.data.message + ' Por favor, atento a las notificaciones de la aplicación para ver el resultado de la carga ya que ahi se mostraran los errores y resultados de la misma. Puede cerrar este dialogo y esperar la notificaci. ',
                    confirmButtonText: 'Aceptar'
                });
            } else {
                await Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: response.data.message || 'Error al procesar el archivo'
                });
            }

        } catch (error: any) {
            hideLoading();
            console.error('Error procesando archivo:', error);

            const statusCode = error.response?.status;
            const mensajeError = error.response?.data?.message || 'Error al procesar el archivo';

            switch (statusCode) {
                case 400:
                    await Swal.fire({
                        icon: 'error',
                        title: 'Error 400 - Solicitud Incorrecta',
                        text: mensajeError || 'La solicitud contiene datos inválidos o mal formateados'
                    });
                    break;

                case 401:
                    await Swal.fire({
                        icon: 'error',
                        title: 'Error 401 - No Autorizado',
                        text: mensajeError || 'No tienes autorización para realizar esta acción. Por favor, inicia sesión nuevamente'
                    });
                    break;

                case 403:
                    await Swal.fire({
                        icon: 'error',
                        title: 'Error 403 - Acceso Prohibido',
                        text: mensajeError || 'No tienes permisos para realizar esta operación'
                    });
                    break;

                case 404:
                    await Swal.fire({
                        icon: 'error',
                        title: 'Error 404 - No Encontrado',
                        text: mensajeError || 'El recurso o endpoint solicitado no fue encontrado'
                    });
                    break;

                case 419:
                    await Swal.fire({
                        icon: 'error',
                        title: 'Error 419 - Token Expirado',
                        text: mensajeError || 'Tu sesión ha expirado. Por favor, recarga la página e intenta nuevamente'
                    });
                    break;

                case 422:
                    const errorsArray = error.response?.data?.errors || [];
                    if (Array.isArray(errorsArray) && errorsArray.length > 0) {
                        setErroresValidacion(errorsArray);
                        setListErrors(true);
                    }
                    await Swal.fire({
                        icon: 'error',
                        title: 'Error 422 - Error de Validación',
                        text: mensajeError || 'Los datos proporcionados no pasaron la validación. Por favor, revisa el archivo'
                    });
                    break;

                default:
                    await Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: mensajeError || 'Error al procesar el archivo'
                    });
                    break;
            }
        }
    };

    const descargarPlantilla = async (e?: React.MouseEvent) => {
        try {
            if (e) e.stopPropagation();
            showLoading('Descargando plantilla...');

            // Los interceptores globales se encargan del token CSRF
            const response = await window.axios.get(route('configuracion.plantilla.global-audax'), {
                responseType: 'blob'
            });

            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `plantilla_global_audax_${new Date().getTime()}.xls`);
            document.body.appendChild(link);
            link.click();
            link.remove();
            window.URL.revokeObjectURL(url);
            hideLoading();
        } catch (error) {
            console.error('Error descargando plantilla:', error);
            hideLoading();
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'No se pudo descargar la plantilla'
            });
        }
    };

    const handleClickUpload = () => {
        fileInputRef.current?.click();
    };

    const handleLimpiar = () => {
        setArchivo(null);
        setDatosExcel([]);
        setColumnas([]);
        setColumnasOriginales([]);
        setError('');
        setResultado(null);
        setListErrors(false);
        setErroresValidacion([]);
        setShowModal(false);
        setErroresFilaSeleccionada(null);
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }
    };

    const handleVerErrores = (errorFila: ErrorValidacion) => {
        setErroresFilaSeleccionada(errorFila);
        setShowModal(true);
    };

    const handleCloseModal = () => {
        setShowModal(false);
        setErroresFilaSeleccionada(null);
    };

    const scrollLeftErrors = () => {
        if (tableErrorsRef.current) {
            tableErrorsRef.current.scrollBy({ left: -300, behavior: 'smooth' });
        }
    };

    const scrollRightErrors = () => {
        if (tableErrorsRef.current) {
            tableErrorsRef.current.scrollBy({ left: 300, behavior: 'smooth' });
        }
    };

    const scrollLeft = () => {
        if (tableContainerRef.current) {
            tableContainerRef.current.scrollBy({ left: -300, behavior: 'smooth' });
        }
    };

    const scrollRight = () => {
        if (tableContainerRef.current) {
            tableContainerRef.current.scrollBy({ left: 300, behavior: 'smooth' });
        }
    };

    return (
        <Layout>
            <Head title={titulo} />
            <div className="page-content">
                <Container fluid>
                    <Row>
                        <Col lg={12}>
                            <Card>
                                <Card.Header className="d-flex justify-content-between align-items-center">
                                    <h4 className="card-title mb-0">
                                        <i className="ri-flashlight-line me-2"></i>
                                        {titulo}
                                    </h4>
                                    <Button
                                        variant="outline-primary"
                                        size="sm"
                                        onClick={descargarPlantilla}
                                    >
                                        <Download className="me-1" size={16} />
                                        Descargar Plantilla
                                    </Button>
                                </Card.Header>
                                <Card.Body>
                                    {error && (
                                        <Alert variant="danger" dismissible onClose={() => setError('')}>
                                            <i className="ri-error-warning-line me-2"></i>
                                            {error}
                                        </Alert>
                                    )}

                                    <div
                                        className={`position-relative ${styles.uploadZone} ${isDragging ? styles.uploadZoneDragging : ''} ${archivo ? styles.uploadZoneHasFile : ''}`}
                                        onDragEnter={handleDragEnter}
                                        onDragOver={handleDragOver}
                                        onDragLeave={handleDragLeave}
                                        onDrop={handleDrop}
                                        onClick={handleClickUpload}
                                    >
                                        <input
                                            ref={fileInputRef}
                                            type="file"
                                            accept=".xlsx,.xls,.csv"
                                            onChange={handleFileInput}
                                            style={{ display: 'none' }}
                                        />

                                        {!archivo ? (
                                            <>
                                                <i className={`ri-upload-cloud-2-line ${styles.uploadIcon}`}></i>
                                                <div className={styles.uploadTitle}>Arrastra tu archivo Excel aquí</div>
                                                <p className={`text-muted ${styles.uploadSubtitle}`}>o haz clic para seleccionar</p>
                                                <p className={`text-muted ${styles.uploadSmallText}`}>
                                                    Formatos aceptados: .xlsx, .xls, .csv (máx. 10MB)
                                                </p>
                                            </>
                                        ) : (
                                            <>
                                                <i className={`ri-file-excel-2-line ${styles.uploadIconSuccess}`}></i>
                                                <div className={`text-success ${styles.uploadTitle}`}>
                                                    <i className="ri-check-line me-1"></i>
                                                    Archivo cargado exitosamente
                                                </div>
                                                <p className={`text-muted ${styles.uploadFileInfo}`}>
                                                    <strong>{archivo.name}</strong>
                                                </p>
                                                <p className={`text-muted ${styles.uploadSmallText}`}>
                                                    Tamaño: {(archivo.size / 1024).toFixed(2)} KB | Registros: <strong>{datosExcel.length}</strong>
                                                </p>
                                                <Button
                                                    variant="outline-danger"
                                                    size="sm"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        handleLimpiar();
                                                    }}
                                                    className="mt-1"
                                                    style={{ fontSize: '0.75rem', padding: '0.25rem 0.5rem' }}
                                                >
                                                    <i className="ri-close-line me-1"></i>
                                                    Limpiar
                                                </Button>
                                            </>
                                        )}
                                    </div>

                                    {datosExcel.length > 0 && (
                                        <div className="mt-4">
                                            <div className="d-flex justify-content-between align-items-center mb-3">
                                                <h5 className="mb-0">
                                                    <i className="ri-table-line me-2"></i>
                                                    Vista Previa de Datos
                                                </h5>
                                                <div className="d-flex gap-2">
                                                    <Button
                                                        onClick={handleProcesar}
                                                        className={styles.btnProcesar}
                                                    >
                                                        <i className="ri-play-line me-2"></i>
                                                        Procesar Carga Global Audax
                                                    </Button>
                                                </div>
                                            </div>

                                            <div className="d-flex justify-content-end mb-2 gap-2" style={{ position: 'relative' }}>
                                                <button
                                                    type="button"
                                                    className={`btn btn-sm ${styles.scrollButton}`}
                                                    onClick={scrollLeft}
                                                    title="Desplazar a la izquierda"
                                                >
                                                    <ChevronLeft size={16} /> Izquierda
                                                </button>

                                                <button
                                                    type="button"
                                                    className={`btn btn-sm ${styles.scrollButton}`}
                                                    onClick={scrollRight}
                                                    title="Desplazar a la derecha"
                                                >
                                                    <ChevronRight size={16} /> Derecha
                                                </button>
                                            </div>

                                            <div ref={tableContainerRef} className={`table-responsive ${styles.tableWrapper}`}>
                                                <Table bordered hover size="sm">
                                                    <thead className={styles.tableHeader} style={{ position: 'sticky', top: 0, zIndex: 10 }}>
                                                        <tr>
                                                            <th style={{ width: '60px' }}>#</th>
                                                            {columnas.map((col, index) => (
                                                                <th key={index}>{col}</th>
                                                            ))}
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {datosExcel.map((row, rowIndex) => (
                                                            <tr key={rowIndex} className={styles.tableRow}>
                                                                <td className={`${styles.tableCell} ${styles.tableCellIndex}`}>{rowIndex + 1}</td>
                                                                {columnasOriginales.map((colOriginal, colIndex) => (
                                                                    <td key={colIndex} className={styles.tableCell}>{row[colOriginal]}</td>
                                                                ))}
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </Table>
                                            </div>

                                            <Alert variant="info" className="mt-3">
                                                <i className="ri-information-line me-2"></i>
                                                <strong>Total de registros:</strong> {datosExcel.length} listos para procesar
                                            </Alert>

                                            {/*
                                            {resultado && (
                                                <div className="mt-4">
                                                    <h5 className="mb-3">
                                                        <FileSpreadsheet className="me-2" size={20} />
                                                        Resultados del Procesamiento
                                                    </h5>

                                                    <Row className="g-3 mb-4">
                                                        <Col md={3} sm={6}>
                                                            <Card className="border-primary">
                                                                <Card.Body className="text-center">
                                                                    <AlertCircle className="text-primary mb-2" size={28} />
                                                                    <h3 className="mb-1">{resultado.total}</h3>
                                                                    <p className="text-muted mb-0 small">Total</p>
                                                                </Card.Body>
                                                            </Card>
                                                        </Col>
                                                        <Col md={3} sm={6}>
                                                            <Card className="border-success">
                                                                <Card.Body className="text-center">
                                                                    <CheckCircle className="text-success mb-2" size={28} />
                                                                    <h3 className="mb-1">{resultado.exitosos}</h3>
                                                                    <p className="text-muted mb-0 small">Exitosos</p>
                                                                </Card.Body>
                                                            </Card>
                                                        </Col>
                                                        <Col md={2} sm={4}>
                                                            <Card className="border-info">
                                                                <Card.Body className="text-center">
                                                                    <CheckCircle className="text-info mb-2" size={28} />
                                                                    <h3 className="mb-1">{resultado.creados}</h3>
                                                                    <p className="text-muted mb-0 small">Creados</p>
                                                                </Card.Body>
                                                            </Card>
                                                        </Col>
                                                        <Col md={2} sm={4}>
                                                            <Card className="border-warning">
                                                                <Card.Body className="text-center">
                                                                    <AlertCircle className="text-warning mb-2" size={28} />
                                                                    <h3 className="mb-1">{resultado.actualizados}</h3>
                                                                    <p className="text-muted mb-0 small">Actualizados</p>
                                                                </Card.Body>
                                                            </Card>
                                                        </Col>
                                                        <Col md={2} sm={4}>
                                                            <Card className="border-secondary">
                                                                <Card.Body className="text-center">
                                                                    <AlertCircle className="text-secondary mb-2" size={28} />
                                                                    <h3 className="mb-1">{resultado.omitidos}</h3>
                                                                    <p className="text-muted mb-0 small">Omitidos</p>
                                                                </Card.Body>
                                                            </Card>
                                                        </Col>
                                                    </Row>

                                                    {resultado.errores > 0 && (
                                                        <Alert variant="danger">
                                                            <div className="d-flex align-items-center mb-2">
                                                                <XCircle className="me-2" size={20} />
                                                                <strong>Errores encontrados: {resultado.errores}</strong>
                                                            </div>
                                                            <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
                                                                <Table size="sm" bordered hover className="mb-0">
                                                                    <thead>
                                                                        <tr>
                                                                            <th style={{ width: '80px' }}>Fila</th>
                                                                            <th>Error</th>
                                                                        </tr>
                                                                    </thead>
                                                                    <tbody>
                                                                        {resultado.detalles_errores.map((detalle, idx) => (
                                                                            <tr key={idx}>
                                                                                <td className="text-center">{detalle.fila}</td>
                                                                                <td>{detalle.error}</td>
                                                                            </tr>
                                                                        ))}
                                                                    </tbody>
                                                                </Table>
                                                            </div>
                                                        </Alert>
                                                    )}
                                                </div>
                                            )}
                                            */}
                                        </div>
                                    )}

                                    {listErrors && erroresValidacion.length > 0 && (
                                        <div className="mt-4">
                                            <div className="d-flex justify-content-between align-items-center mb-3">
                                                <h5 className="mb-0">
                                                    <i className="ri-error-warning-line me-2 text-danger"></i>
                                                    Errores de Validación
                                                </h5>
                                            </div>

                                            <div className="d-flex justify-content-end mb-2 gap-2" style={{ position: 'relative' }}>
                                                <button
                                                    type="button"
                                                    className={`btn btn-sm ${styles.scrollButton}`}
                                                    onClick={scrollLeftErrors}
                                                    title="Desplazar a la izquierda"
                                                >
                                                    <ChevronLeft size={16} /> Izquierda
                                                </button>

                                                <button
                                                    type="button"
                                                    className={`btn btn-sm ${styles.scrollButton}`}
                                                    onClick={scrollRightErrors}
                                                    title="Desplazar a la derecha"
                                                >
                                                    <ChevronRight size={16} /> Derecha
                                                </button>
                                            </div>

                                            <div ref={tableErrorsRef} className={`table-responsive ${styles.tableWrapper}`}>
                                                <Table bordered hover size="sm">
                                                    <thead className={styles.tableHeader} style={{ position: 'sticky', top: 0, zIndex: 10 }}>
                                                        <tr>
                                                            <th style={{ width: '100px' }}>Fila</th>
                                                            <th style={{ width: '200px' }}>Errores</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {erroresValidacion.map((errorFila, index) => (
                                                            <tr key={index} className={styles.tableRow}>
                                                                <td className={`${styles.tableCell} ${styles.tableCellIndex} text-center`}>
                                                                    {errorFila.fila}
                                                                </td>
                                                                <td className={styles.tableCell} style={{ width: '200px' }}>
                                                                    <Button
                                                                        variant="outline-danger"
                                                                        size="sm"
                                                                        onClick={() => handleVerErrores(errorFila)}
                                                                        style={{ whiteSpace: 'nowrap' }}
                                                                    >
                                                                        <XCircle className="me-1" size={16} />
                                                                        Ver {errorFila.errores.length} {errorFila.errores.length === 1 ? 'error' : 'errores'}
                                                                    </Button>
                                                                </td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </Table>
                                            </div>

                                            <Alert variant="danger" className="mt-3">
                                                <i className="ri-error-warning-line me-2"></i>
                                                <strong>Total de filas con errores:</strong> {erroresValidacion.length}
                                            </Alert>
                                        </div>
                                    )}
                                </Card.Body>
                            </Card>
                        </Col>
                    </Row>
                </Container>
            </div>

            {/* Modal para mostrar errores de una fila */}
            <Modal show={showModal} onHide={handleCloseModal} size="lg" centered>
                <Modal.Header closeButton>
                    <Modal.Title>
                        <XCircle className="me-2 text-danger" size={24} />
                        Errores de Validación - Fila {erroresFilaSeleccionada?.fila}
                    </Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    {erroresFilaSeleccionada && erroresFilaSeleccionada.errores.length > 0 ? (
                        <div>
                            <Alert variant="warning" className="mb-3">
                                <strong>Total de errores en esta fila:</strong> {erroresFilaSeleccionada.errores.length}
                            </Alert>
                            <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
                                <Table bordered hover size="sm">
                                    <thead>
                                        <tr>
                                            <th style={{ width: '60px' }}>#</th>
                                            <th>Error</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {erroresFilaSeleccionada.errores.map((errorMsg, idx) => (
                                            <tr key={idx}>
                                                <td className="text-center">{idx + 1}</td>
                                                <td>
                                                    <div className="text-danger">
                                                        <i className="ri-close-circle-line me-2"></i>
                                                        {errorMsg}
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </Table>
                            </div>
                        </div>
                    ) : (
                        <Alert variant="info">
                            No hay errores para mostrar
                        </Alert>
                    )}
                </Modal.Body>
                <Modal.Footer>
                    <Button variant="secondary" onClick={handleCloseModal}>
                        Cerrar
                    </Button>
                </Modal.Footer>
            </Modal>
        </Layout>
    );
};

export default CargaGlobalAudax;
