import React from 'react';
import { Alert, Button, Table } from 'react-bootstrap';

interface ProcessHistory {
    id: number;
    numero_proceso: string;
    tipo_proceso: number;
    operacion: any;
    respuesta: any;
    usuario_id: number | null;
    usuario_nombre: string;
    fecha_operacion: string;
    created_at: string;
    updated_at: string;
}

interface AudaxErrorFila {
    fila: number;
    errores: string[];
    campos?: string[];
}

interface CargaGlobalAudaxTableProps {
    histories: ProcessHistory[];
}

const CargaGlobalAudaxTable: React.FC<CargaGlobalAudaxTableProps> = ({ histories }) => {
    const history = histories[0];
    const respuesta = history?.respuesta ?? {};
    const summary = respuesta.summary ?? {};
    const errorFileUrl = respuesta.error_file_url || summary.error_file_url;
    const hasErrors = Boolean(respuesta.has_errors ?? summary.has_errors);

    const rawErrores = respuesta.errores_filas;
    const erroresFilas: AudaxErrorFila[] = Array.isArray(rawErrores)
        ? rawErrores.filter(
              (row: any) =>
                  row &&
                  (typeof row.fila === 'number' || typeof row.fila === 'string') &&
                  Array.isArray(row.errores)
          )
        : [];

    return (
        <div>
            <div className="mb-3">
                <p className="text-muted mb-1">
                    <strong>Total registros:</strong> {summary.total ?? '-'}
                </p>
                <p className="text-muted mb-1">
                    <strong>Procesados:</strong> {summary.procesados ?? '-'}
                </p>
                <p className="text-muted mb-0">
                    <strong>Errores:</strong> {summary.errores ?? 0}
                </p>
            </div>

            {hasErrors ? (
                <Alert variant="warning" className="d-flex align-items-center justify-content-between">
                    <div>
                        <i className="bx bx-error-circle me-2"></i>
                        Se encontraron errores y se corresponde a los campos marcados en rojo dentro del excel.
                        Descarga el archivo para corregirlos.
                    </div>
                    {errorFileUrl && (
                        <Button
                            as="a"
                            href={errorFileUrl}
                            download
                            variant="success"
                            className="ms-3"
                        >
                            <i className="bx bx-download me-1"></i>
                            Descargar
                        </Button>
                    )}
                </Alert>
            ) : (
                <Alert variant="success">
                    <i className="bx bx-check-circle me-2"></i>
                    Proceso completado sin errores.
                </Alert>
            )}

            {!errorFileUrl && hasErrors && (
                <Alert variant="info">
                    <i className="bx bx-info-circle me-2"></i>
                    No hay archivo disponible para descarga.
                </Alert>
            )}

            {erroresFilas.length > 0 && (
                <div className="mt-4">
                    <h6 className="mb-2 fw-semibold">Detalle de validación por fila</h6>
                    <p className="text-muted small mb-2">
                        La columna # empieza en 2: la fila 1 queda reservada al resumen de totales de arriba.
                    </p>
                    <Table responsive bordered hover size="sm" className="mb-0 align-middle">
                        <thead className="table-light">
                            <tr>
                                <th style={{ width: '4rem' }}>#</th>
                                <th style={{ width: '6rem' }}>Fila Excel</th>
                                <th style={{ width: '5rem' }}>Estado</th>
                                <th>Mensajes</th>
                            </tr>
                        </thead>
                        <tbody>
                            {erroresFilas.map((row, idx) => (
                                <tr key={`${row.fila}-${idx}`}>
                                    <td>{idx + 2}</td>
                                    <td className="fw-medium">{row.fila}</td>
                                    <td>
                                        <span className="text-danger fw-semibold small">Error</span>
                                    </td>
                                    <td>
                                        <ul className="mb-0 ps-3">
                                            {row.errores.map((msg, i) => (
                                                <li key={i} className="small">
                                                    {msg}
                                                </li>
                                            ))}
                                        </ul>
                                        {row.campos && row.campos.length > 0 && (
                                            <p className="mb-0 mt-1 text-muted small">
                                                <strong>Campos:</strong> {row.campos.join(', ')}
                                            </p>
                                        )}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </Table>
                </div>
            )}
        </div>
    );
};

export default CargaGlobalAudaxTable;
