import React from 'react';
import { Col, Form } from 'react-bootstrap';
import type { ColProps } from 'react-bootstrap';
import styles from '../css/UniClienteUniPunto.module.css';

export interface CampoInformativoProps {
    id: string;
    etiqueta: string;
    valor: string | number | null | undefined;
    unidad?: string;
    valorVacio?: string;
    colProps?: ColProps;
    esInvalido?: boolean;
    mensajeError?: string;
}

function formatearValor(
    valor: string | number | null | undefined,
    unidad?: string,
    valorVacio = 'Sin dato',
): string {
    if (valor === null || valor === undefined || valor === '') {
        return valorVacio;
    }

    const texto = String(valor);

    return unidad ? `${texto} ${unidad}` : texto;
}

export const CampoInformativo: React.FC<CampoInformativoProps> = ({
    id,
    etiqueta,
    valor,
    unidad,
    valorVacio = 'Sin dato',
    colProps,
    esInvalido = false,
    mensajeError,
}) => {
    const contenido = (
        <>
            <Form.Label htmlFor={id} className={`form-label fw-medium ${styles.etiquetaInformativa}`}>
                {etiqueta}
            </Form.Label>
            <Form.Control
                id={id}
                readOnly
                tabIndex={-1}
                aria-readonly="true"
                aria-invalid={esInvalido}
                aria-describedby={esInvalido && mensajeError ? `${id}-error` : undefined}
                className={`form-control-sm ${styles.campoInformativo} ${esInvalido ? 'is-invalid' : ''}`}
                value={formatearValor(valor, unidad, valorVacio)}
            />
            {esInvalido && mensajeError ? (
                <Form.Control.Feedback type="invalid" id={`${id}-error`}>
                    {mensajeError}
                </Form.Control.Feedback>
            ) : null}
        </>
    );

    if (colProps) {
        return <Col {...colProps}>{contenido}</Col>;
    }

    return <div>{contenido}</div>;
};
