import React, { useState } from 'react';
import { Table, Button, Badge } from 'react-bootstrap';
import { getOkCommercialRowStatus } 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 OkCommercialTableProps {
    histories: ProcessHistory[];
    rowOffset?: number;
}

const OkCommercialTable: React.FC<OkCommercialTableProps> = ({ 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 = getOkCommercialRowStatus(respuesta);

        switch (status) {
            case 'success':
                return <Badge bg="success">Exitoso</Badge>;
            case 'error':
                return <Badge bg="danger">Error</Badge>;
            case 'warning':
                return <Badge bg="warning">Advertencia</Badge>;
            default:
                return <Badge bg="secondary">Desconocido</Badge>;
        }
    };

    // Extraer información de contrato de la operación
    const getContractInfo = (operacion: any): string => {
        if (!operacion) return '-';

        if (operacion.CodCom) {
            const parts = [];
            if (operacion.id_luz) parts.push(`Luz: ${operacion.id_luz}`);
            if (operacion.id_gas) parts.push(`Gas: ${operacion.id_gas}`);
            if (operacion.numeroContrato != null && operacion.tipoContrato) {
                parts.push(`Contrato ${operacion.numeroContrato} (${operacion.tipoContrato})`);
            }
            return parts.length > 0 ? parts.join(' | ') : `CodCom: ${operacion.CodCom}`;
        }

        if (operacion.accion) return operacion.accion;

        return '-';
    };

    return (
        <div className="table-responsive">
            <Table striped bordered hover size="sm">
                <thead className="table-light">
                    <tr>
                        <th style={{ width: '5%' }}>#</th>
                        <th style={{ width: '25%' }}>Contrato</th>
                        <th style={{ width: '30%' }}>Operación</th>
                        <th style={{ width: '20%' }}>Respuesta</th>
                        <th style={{ width: '10%' }}>Estado</th>
                        <th style={{ width: '15%' }}>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>
                                    <small className="text-muted">
                                        {getContractInfo(history.operacion)}
                                    </small>
                                </td>
                                <td>
                                    <div
                                        style={{
                                            maxHeight: '60px',
                                            overflow: 'hidden',
                                            textOverflow: 'ellipsis',
                                        }}
                                    >
                                        <code className="text-muted small">
                                            {typeof history.operacion === 'string'
                                                ? history.operacion.substring(0, 80)
                                                : JSON.stringify(history.operacion).substring(0, 80)}
                                            ...
                                        </code>
                                    </div>
                                </td>
                                <td>
                                    <div
                                        style={{
                                            maxHeight: '60px',
                                            overflow: 'hidden',
                                            textOverflow: 'ellipsis',
                                        }}
                                    >
                                        <code className="text-muted small">
                                            {typeof history.respuesta === 'string'
                                                ? history.respuesta.substring(0, 80)
                                                : JSON.stringify(history.respuesta).substring(0, 80)}
                                            ...
                                        </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={7} className="bg-light">
                                        <div className="p-3">
                                            <div className="row">
                                                <div className="col-md-6">
                                                    <h6 className="fw-semibold mb-2">
                                                        <i className="bx bx-send me-1"></i>
                                                        Operación (Request):
                                                    </h6>
                                                    {renderJsonContent(history.operacion)}
                                                </div>
                                                <div className="col-md-6">
                                                    <h6 className="fw-semibold mb-2">
                                                        <i className="bx bx-message-square-check me-1"></i>
                                                        Respuesta (Response):
                                                    </h6>
                                                    {renderJsonContent(history.respuesta)}
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            )}
                        </React.Fragment>
                    ))}
                </tbody>
            </Table>
        </div>
    );
};

export default OkCommercialTable;
