import { useState, useEffect, useLayoutEffect } from 'react';
import { Typography } from '../../Atoms/Typography/Typography';
import { Icon } from '../../Atoms/Icon/Icon';
import { FONT_FAMILY_MONO } from '../../../designTokens';

export const TenantConfig = ({
  // Título
  title = '',
  titleStyle,
  titleClassName = '',
  
  // Texto/Descripción
  text = '',
  textStyle,
  textClassName = '',
  
  // Icono
  iconName = 'Cog6ToothIcon',
  iconSize = 24,
  iconColor = '#334681',
  iconStyle,
  iconClassName = '',
  
  // Contenedores
  containerStyle,
  containerClassName = '',
  contentContainerStyle,
  contentContainerClassName = '',
  iconContainerStyle,
  iconContainerClassName = '',
  textContainerStyle,
  textContainerClassName = '',
  
  // Breakpoint (resolución): narrow con chevron hasta este ancho; por defecto 1023
  breakpointNarrowPx = 1023,
  
  className = '',
  ...props
}) => {
  const [isNarrow, setIsNarrow] = useState(() =>
    typeof window !== 'undefined' ? window.innerWidth <= breakpointNarrowPx : false
  );
  const [isExpanded, setIsExpanded] = useState(false);

  const updateBreakpoint = () => {
    const narrow = window.innerWidth <= breakpointNarrowPx;
    setIsNarrow(narrow);
    if (!narrow) setIsExpanded(false);
  };

  useLayoutEffect(() => {
    updateBreakpoint();
  }, [breakpointNarrowPx]);

  useEffect(() => {
    window.addEventListener('resize', updateBreakpoint);
    return () => window.removeEventListener('resize', updateBreakpoint);
  }, [breakpointNarrowPx]);

  const isNarrowExpanded = isNarrow && isExpanded;
  const isNarrowCollapsed = isNarrow && !isExpanded;

  return (
    <div
      className={`anima-tenantconfig__container ${containerClassName} ${className}`}
      style={{
        width: '100%',
        minWidth: 0,
        maxWidth: '100%',
        ...(isNarrowCollapsed
          ? { height: '80px', minHeight: '80px' }
          : isNarrowExpanded
            ? { height: 'auto', minHeight: 0 }
            : { height: 'auto', minHeight: 0 }),
        paddingTop: '16px',
        paddingRight: '20px',
        paddingBottom: '16px',
        paddingLeft: '20px',
        gap: '12px',
        borderRadius: '12px',
        border: '1px solid var(--misc-estado-info, #334681)',
        backgroundColor: '#F0F3FC',
        opacity: 1,
        boxSizing: 'border-box',
        display: 'flex',
        flexDirection: 'row',
        alignItems: isNarrow && !isExpanded ? 'center' : 'flex-start',
        overflow: 'hidden',
        ...(containerStyle || {}),
      }}
      {...props}
    >
      {/* Contenedor de la rueda de configuración */}
      <div
        className={`anima-tenantconfig__icon-container ${iconContainerClassName}`}
        style={{
          width: '24px',
          ...(isNarrow
            ? {
                height: '48px',
                minHeight: '48px',
                display: 'flex',
                alignItems: 'center',
                paddingTop: 0,
              }
            : { minHeight: 0, paddingTop: '4px' }),
          opacity: 1,
          boxSizing: 'border-box',
          flexShrink: 0,
          ...(iconContainerStyle || {}),
        }}
      >
        {/* Div rueda configuración - estilo desktop en ambos casos */}
        <div
          style={{
            width: '24px',
            height: '24px',
            opacity: 1,
            boxSizing: 'border-box',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            position: 'relative',
          }}
        >
          <Icon
            name={iconName}
            size={24}
            className={iconClassName}
            style={{
              width: '24px',
              height: '24px',
              opacity: 1,
              color: iconColor,
              stroke: '#334681',
              strokeWidth: '1.5px',
              ...(iconStyle || {}),
            }}
          />
        </div>
      </div>

      {/* Contenedor del texto (título + descripción) */}
      <div
        className={`anima-tenantconfig__text-container ${textContainerClassName}`}
        style={{
          flex: '1 1 auto',
          minWidth: 0,
          ...(isNarrowCollapsed
            ? { height: '48px', minHeight: '48px' }
            : { minHeight: 0 }),
          ...(isNarrowExpanded && { maxWidth: '332px' }),
          gap: isNarrowExpanded ? '10px' : '8px',
          opacity: 1,
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'flex-start',
          justifyContent: isNarrowCollapsed ? 'center' : 'flex-start',
          ...(textContainerStyle || {}),
        }}
      >
        {/* Div título (en narrow igual colapsado o expandido) */}
        {title && (
          <div
            className={`anima-tenantconfig__title-container`}
            style={{
              width: '100%',
              ...(isNarrow ? { width: '100%', minWidth: 0, height: '48px', minHeight: 0, display: 'flex', alignItems: 'center' } : { minHeight: '30px' }),
              gap: '8px',
              opacity: 1,
              boxSizing: 'border-box',
            }}
          >
            <Typography
              variant="mono-md"
              className={titleClassName}
              style={{
                fontFamily: FONT_FAMILY_MONO,
                fontWeight: 500,
                fontStyle: 'normal',
                fontSize: isNarrow ? '16px' : '20px',
                lineHeight: isNarrow ? '24px' : '30px',
                letterSpacing: '0%',
                verticalAlign: 'middle',
                color: '#334681',
                margin: 0,
                ...(titleStyle || {}),
              }}
            >
              {title}
            </Typography>
          </div>
        )}

        {/* Div texto: en narrow colapsado no se muestra; en narrow expandido bloque 332+288; en desktop normal */}
        {text && !isNarrowCollapsed && (
          <>
            {isNarrowExpanded ? (
              <div
                className="anima-tenantconfig__text-expanded-wrapper"
                style={{
                  width: '100%',
                  maxWidth: '332px',
                  minHeight: 0,
                  paddingRight: '8px',
                  gap: '10px',
                  opacity: 1,
                  boxSizing: 'border-box',
                  display: 'flex',
                  flexDirection: 'column',
                }}
              >
                <div
                  className="anima-tenantconfig__text-content anima-tenantconfig__text-content--expanded"
                  style={{
                    width: '100%',
                    maxWidth: '288px',
                    minHeight: 0,
                    opacity: 1,
                    boxSizing: 'border-box',
                  }}
                >
                  <Typography
                    variant="mono-md"
                    className={textClassName}
                    style={{
                      fontFamily: FONT_FAMILY_MONO,
                      fontWeight: 450,
                      fontStyle: 'normal',
                      fontSize: '14px',
                      lineHeight: '21px',
                      letterSpacing: '0.01em',
                      verticalAlign: 'middle',
                      color: 'var(--misc-estado-info, #334681)',
                      margin: 0,
                      ...(textStyle || {}),
                    }}
                  >
                    {text}
                  </Typography>
                </div>
              </div>
            ) : (
              <div
                className={`anima-tenantconfig__text-content`}
                style={{
                  width: '100%',
                  minHeight: 0,
                  opacity: 1,
                  boxSizing: 'border-box',
                  display: 'block',
                }}
              >
                <Typography
                  variant="mono-md"
                  className={textClassName}
                  style={{
                    fontFamily: FONT_FAMILY_MONO,
                    fontWeight: 450,
                    fontStyle: 'normal',
                    fontSize: '14px',
                    lineHeight: '21px',
                    letterSpacing: '0.01em',
                    verticalAlign: 'middle',
                    color: 'var(--misc-estado-info, #334681)',
                    margin: 0,
                    ...(textStyle || {}),
                  }}
                >
                  {text}
                </Typography>
              </div>
            )}
          </>
        )}
      </div>

      {/* Chevron (solo por debajo de 1024px); click alterna expandido/colapsado */}
      {isNarrow && (
        <button
          type="button"
          className="anima-tenantconfig__chevron"
          onClick={() => setIsExpanded((e) => !e)}
          style={{
            width: '20px',
            height: '42px',
            marginLeft: 'auto',
            opacity: 1,
            borderRadius: '4px',
            boxSizing: 'border-box',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexShrink: 0,
            border: 'none',
            background: 'transparent',
            cursor: 'pointer',
            padding: 0,
          }}
          aria-expanded={isExpanded}
          aria-label={isExpanded ? 'Contraer' : 'Expandir'}
        >
          <Icon
            name={isExpanded ? 'ChevronUpIcon' : 'ChevronDownIcon'}
            size={20}
            style={{
              width: '20px',
              height: '20px',
              color: 'var(--misc-estado-info, #334681)',
            }}
          />
        </button>
      )}
    </div>
  );
};

export default TenantConfig;

