import React, { useState } from 'react';
import { Table, Button } from 'react-bootstrap';
import { getIntegracionRowStatus } from '../processHistoryStatus';

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 ProcessIntegrationTableProps {
    histories: ProcessHistory[];
    /** Índice global de la primera fila (paginación); por defecto 0 → # = 1, 2, … */
    rowOffset?: number;
}

const ProcessIntegrationTable: React.FC<ProcessIntegrationTableProps> = ({ histories, rowOffset = 0 }) => {
    const [expandedRows, setExpandedRows] = useState<Set<number>>(new Set());

    const toggleRowExpansion = (id: number) => {
        setExpandedRows((prev) => {
            const newSet = new Set(prev);
            if (newSet.has(id)) {
                newSet.delete(id);
            } else {
                newSet.add(id);
            }
            return newSet;
        });
    };

    const formatDate = (dateString: string): string => {
        const date = new Date(dateString);
        return date.toLocaleString('es-ES', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
        });
    };

    const renderJsonContent = (data: any): JSX.Element => {
        if (!data) return <span className="text-muted">-</span>;

        const jsonString = typeof data === 'string' ? data : JSON.stringify(data, null, 2);

        return (
            <pre
                className="mb-0"
                style={{
                    maxHeight: '200px',
                    overflow: 'auto',
                    fontSize: '12px',
                    backgroundColor: '#f8f9fa',
                    padding: '8px',
                    borderRadius: '4px',
                }}
            >
                {jsonString}
            </pre>
        );
    };

    const getStatusBadge = (respuesta: any): JSX.Element => {
        const status = getIntegracionRowStatus(respuesta);

        switch (status) {
            case 'success':
                return <span className="badge bg-success">Exitoso</span>;
            case 'error':
                return <span className="badge bg-danger">Error</span>;
            default:
                return <span className="badge bg-secondary">Desconocido</span>;
        }
    };

    return (
        <div className="table-responsive">
            <Table striped bordered hover size="sm">
                <thead className="table-light">
                    <tr>
                        <th style={{ width: '5%' }}>#</th>
                        <th style={{ width: '30%' }}>Operación</th>
                        <th style={{ width: '30%' }}>Respuesta</th>
                        <th style={{ width: '10%' }}>Estado</th>
                        <th style={{ width: '20%' }}>Fecha</th>
                        <th style={{ width: '5%' }}>Detalles</th>
                    </tr>
                </thead>
                <tbody>
                    {histories.map((history, index) => (
                        <React.Fragment key={history.id}>
                            <tr>
                                <td className="text-center">{rowOffset + index + 1}</td>
                                <td>
                                    <div
                                        style={{
                                            maxHeight: '80px',
                                            overflow: 'hidden',
                                            textOverflow: 'ellipsis',
                                        }}
                                    >
                                        <code className="text-muted small">
                                            {typeof history.operacion === 'string'
                                                ? history.operacion.substring(0, 100)
                                                : JSON.stringify(history.operacion).substring(0, 100)}
                                            ...
                                        </code>
                                    </div>
                                </td>
                                <td>
                                    <div
                                        style={{
                                            maxHeight: '80px',
                                            overflow: 'hidden',
                                            textOverflow: 'ellipsis',
                                        }}
                                    >
                                        <code className="text-muted small">
                                            {typeof history.respuesta === 'string'
                                                ? history.respuesta.substring(0, 100)
                                                : JSON.stringify(history.respuesta).substring(0, 100)}
                                            ...
                                        </code>
                                    </div>
                                </td>
                                <td className="text-center">{getStatusBadge(history.respuesta)}</td>
                                <td>
                                    <small>{formatDate(history.fecha_operacion)}</small>
                                </td>
                                <td className="text-center">
                                    <Button
                                        variant="link"
                                        size="sm"
                                        onClick={() => toggleRowExpansion(history.id)}
                                    >
                                        <i
                                            className={`bx bx-chevron-${
                                                expandedRows.has(history.id) ? 'up' : 'down'
                                            }`}
                                        ></i>
                                    </Button>
                                </td>
                            </tr>
                            {expandedRows.has(history.id) && (
                                <tr>
                                    <td colSpan={6} className="bg-light">
                                        <div className="p-3">
                                            <div className="row">
                                                <div className="col-md-6">
                                                    <h6 className="fw-semibold mb-2">
                                                        Operación (Request):
                                                    </h6>
                                                    {renderJsonContent(history.operacion)}
                                                </div>
                                                <div className="col-md-6">
                                                    <h6 className="fw-semibold mb-2">
                                                        Respuesta (Response):
                                                    </h6>
                                                    {renderJsonContent(history.respuesta)}
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            )}
                        </React.Fragment>
                    ))}
                </tbody>
            </Table>
        </div>
    );
};

export default ProcessIntegrationTable;
