import { useState, useEffect, useRef } from 'react';
import { Icon } from '../Icon/Icon';
import { Tooltip } from '../Tooltip/Tooltip';
import { FONT_FAMILY_SANS } from '../../../designTokens';

const BREAKPOINT_NARROW = 768;

/**
 * Badge informativo: rectángulo.
 * - Pantalla ancha: altura 30px, ancho al contenido, márgenes laterales 10px, texto en una línea (ellipsis + tooltip si trunca).
 * - Pantalla estrecha (mobile): ancho 100%, sin márgenes, texto colapsa (varias líneas), altura crece, icono centrado verticalmente.
 * Borde de 1px y 8px de radio. Tipo: info (azul), error (rojo) o success (verde).
 */
const ICON_POR_TIPO = {
  info: 'LinkSlashIcon',
  error: 'LinkSlashIcon',
  success: 'LinkSlashIcon',
};

const COLOR_ICON_POR_TIPO = {
  info: 'blue-600',
  error: 'red-600',
  success: 'green-600',
};

export const BadgeInformativo = ({
  text = '',
  type = 'info',
  className = '',
  style,
  ...props
}) => {
  const colores = {
    info: '#2563EB',
    error: '#FF0000',
    success: '#16A34A',
  };
  const color = colores[type] ?? colores.info;
  const iconName = ICON_POR_TIPO[type] ?? ICON_POR_TIPO.info;
  const iconColor = COLOR_ICON_POR_TIPO[type] ?? COLOR_ICON_POR_TIPO.info;

  const [isNarrow, setIsNarrow] = useState(() =>
    typeof window !== 'undefined' ? window.innerWidth <= BREAKPOINT_NARROW : false
  );
  const [isTruncated, setIsTruncated] = useState(false);
  const textRef = useRef(null);

  useEffect(() => {
    const onResize = () => setIsNarrow(window.innerWidth <= BREAKPOINT_NARROW);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  const checkTruncation = () => {
    const el = textRef.current;
    if (!el) return;
    setIsTruncated(el.scrollWidth > el.clientWidth);
  };

  const setTextRef = (el) => {
    textRef.current = el;
    if (el) requestAnimationFrame(checkTruncation);
  };

  useEffect(() => {
    let observer;
    const rafId = requestAnimationFrame(() => {
      checkTruncation();
      const el = textRef.current;
      if (el) {
        observer = new ResizeObserver(() => requestAnimationFrame(checkTruncation));
        observer.observe(el);
      }
    });
    return () => {
      cancelAnimationFrame(rafId);
      if (observer) observer.disconnect();
    };
  }, [text, isNarrow]);

  return (
    <div
      className={`anima-badgeinformativo ${className}`}
      style={{
        minHeight: '30px',
        height: isNarrow ? 'auto' : '30px',
        width: isNarrow ? '100%' : 'fit-content',
        maxWidth: isNarrow ? '100%' : undefined,
        marginLeft: isNarrow ? 0 : '10px',
        marginRight: isNarrow ? 0 : '10px',
        borderRadius: '8px',
        border: `1px solid ${color}`,
        backgroundColor: '#FFFFFF',
        boxSizing: 'border-box',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'flex-start',
        paddingTop: isNarrow ? '0.5rem' : undefined,
        paddingBottom: isNarrow ? '0.5rem' : undefined,
        paddingLeft: '1rem',
        paddingRight: '1rem',
        gap: '1rem',
        ...style,
      }}
      {...props}
    >
      <Icon
        name={iconName}
        size={16}
        color={iconColor}
        strokeWidth={2}
        style={{ flexShrink: 0, ...(type === 'error' ? { color: '#FF0000' } : {}) }}
      />
      <div
        style={{
          minWidth: 0,
          flex: 1,
          overflow: isNarrow ? 'visible' : 'hidden',
          display: 'flex',
          alignItems: 'center',
          alignSelf: 'stretch',
          height: isNarrow ? undefined : '100%',
        }}
      >
        {!isNarrow && isTruncated ? (
          <Tooltip content={text} position="bottom" style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
            <span
              ref={setTextRef}
              style={{
                color,
                fontFamily: FONT_FAMILY_SANS,
                fontWeight: 400,
                fontStyle: 'normal',
                fontSize: '14px',
                lineHeight: '21px',
                letterSpacing: '0%',
                direction: 'ltr',
                textAlign: 'left',
                verticalAlign: 'middle',
                textTransform: 'uppercase',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                display: 'block',
              }}
            >
              {text}
            </span>
          </Tooltip>
        ) : (
          <span
            ref={setTextRef}
            style={{
              color,
              fontFamily: FONT_FAMILY_SANS,
              fontWeight: 400,
              fontStyle: 'normal',
              fontSize: '14px',
              lineHeight: '21px',
              letterSpacing: '0%',
              direction: 'ltr',
              textAlign: 'left',
              verticalAlign: 'middle',
              textTransform: 'uppercase',
              whiteSpace: isNarrow ? 'normal' : 'nowrap',
              overflow: isNarrow ? 'visible' : 'hidden',
              textOverflow: isNarrow ? undefined : 'ellipsis',
              display: 'block',
              wordBreak: isNarrow ? 'break-word' : undefined,
            }}
          >
            {text}
          </span>
        )}
      </div>
    </div>
  );
};

export default BadgeInformativo;
