import { useState, useEffect, useLayoutEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Typography } from '../../Atoms/Typography/Typography';
import { Icon } from '../../Atoms/Icon/Icon';
import { Badge } from '../../Atoms/Badge/Badge';
import { BadgeInformativo } from '../../Atoms/BadgeInformativo/BadgeInformativo';
import { FONT_FAMILY_SANS, FONT_FAMILY_MONO } from '../../../designTokens';

const BREAKPOINT_NARROW = 769;
const MOBILE_MAX_WIDTH = 768; // de 0 a 768px se ocultan los iconos

export const ConfiguracionOverview = ({
  // Título principal
  title = 'Configuración inicial',
  titleStyle,
  titleClassName = '',

  // Badge informativo encima del overview (1rem de distancia)
  badgeText = 'Contenido sin funcionalidad definida, no conectado a Backend.',
  badgeType = 'error',

  // Contenido (children o contenido renderizable)
  children,

  // Lista de ítems del panel inferior: cada uno con estado 'Completado' o 'Pendiente' (modificable por el padre)
  slotStates = ['Completado', 'Completado', 'Pendiente', 'Pendiente', 'Pendiente'],

  // Títulos y subtítulos por ítem (5 elementos). El rectángulo de arriba = título, el de abajo = subtítulo.
  slotTitles = [
    'Tenant configurado (nombre/idioma/timezone/logo)',
    'Administradores existentes (al menos 1)',
    'Integración SSO/AD',
    'Configuración de Roles RBAC',
    'Empresas',
  ],
  slotSubtitles = [
    'Parámetros básicos de identidad y localización definidos.',
    'Acceso técnico de administración garantizado.',
    'Conexión con el proveedor de identidad externa.',
    'Definición de matrices de permisos y perfiles.',
    'Carga de razones sociales y estructura legal.',
  ],

  // Callback al cambiar el estado de un ítem: (índice0Based, nuevoEstado) => {} — el padre debe actualizar slotStates
  onSlotStateChange,

  // Contenedores
  containerStyle,
  containerClassName = '',
  titleContainerStyle,
  titleContainerClassName = '',
  contentContainerStyle,
  contentContainerClassName = '',

  className = '',
  ...props
}) => {
  const { t } = useTranslation();
  const completedState = t('overview.taskCompleted', { defaultValue: 'Completado' });
  const isCompletedState = (value) => {
    const normalized = String(value ?? '').trim().toLowerCase();
    return normalized === String(completedState).trim().toLowerCase()
      || normalized === 'completado'
      || normalized === 'completed';
  };
  const [isNarrow, setIsNarrow] = useState(() =>
    typeof window !== 'undefined' ? window.innerWidth <= BREAKPOINT_NARROW : false
  );
  const [showIcons, setShowIcons] = useState(() =>
    typeof window !== 'undefined' ? window.innerWidth > MOBILE_MAX_WIDTH : true
  );

  const updateBreakpoint = () => {
    const w = window.innerWidth;
    setIsNarrow(w <= BREAKPOINT_NARROW);
    setShowIcons(w > MOBILE_MAX_WIDTH);
  };

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

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

  return (
    <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: '1rem' }}>
      <BadgeInformativo text={badgeText} type={badgeType} />
      <div
        className={`anima-configuracionoverview__container ${containerClassName} ${className}`}
        style={{
          width: '100%',
          minWidth: 0,
          height: showIcons ? '490px' : 'auto',
          minHeight: showIcons ? undefined : '490px',
          borderRadius: 'var(--radius-16, 16px)',
          border: '1px solid var(--color-grey-200, #c4c4c4)',
          backgroundColor: 'var(--color-neutrals-white, #FFFFFF)',
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
          ...(containerStyle || {}),
        }}
        {...props}
      >
      {/* Contenedor del título */}
      <div
        className={`anima-configuracionoverview__title-container ${titleContainerClassName}`}
        style={{
          width: '100%',
          minHeight: 0,
          flexShrink: 0,
          paddingTop: '24px',
          paddingRight: 'var(--space-16, 1rem)',
          paddingBottom: '4px',
          paddingLeft: 'var(--space-16, 1rem)',
          gap: '8px',
          opacity: 1,
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'column',
          ...(titleContainerStyle || {}),
        }}
      >
        <div
          style={{
            width: '100%',
            minHeight: 0,
            minWidth: 0,
            boxSizing: 'border-box',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: '12px',
          }}
        >
          {title && (
            <Typography
              variant="h5"
              className={titleClassName}
              style={{
                fontFamily: FONT_FAMILY_SANS,
                fontWeight: 500,
                fontStyle: 'normal',
                fontSize: '24px',
                lineHeight: '36px',
                letterSpacing: '0%',
                verticalAlign: 'middle',
                color: 'var(--color-cyan-19)',
                margin: 0,
                flex: '1 1 auto',
                minWidth: 0,
                ...(titleStyle || {}),
              }}
            >
              {title}
            </Typography>
          )}
          {showIcons && (
            <div style={{ flexShrink: 0, height: '24px', display: 'flex', alignItems: 'center' }}>
              <Badge
                variant="success"
                size="small"
                className="anima-configuracionoverview__title-badge"
                style={{
                  height: '24px',
                  minWidth: '96px',
                  opacity: 1,
                  borderRadius: 'var(--radius-16, 16px)',
                  paddingTop: '2px',
                  paddingRight: '12px',
                  paddingBottom: '4px',
                  paddingLeft: '12px',
                  backgroundColor: 'var(--color-cyan-82, #B8E2E9)',
                  fontFamily: FONT_FAMILY_MONO,
                  fontWeight: 400,
                  fontStyle: 'normal',
                  fontSize: '12px',
                  lineHeight: '18px',
                  letterSpacing: '0%',
                  textAlign: 'right',
                  verticalAlign: 'middle',
                  color: 'var(--color-grey-700, #474747)',
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'flex-end',
                  boxSizing: 'border-box',
                }}
              >
                {slotStates.filter((s) => isCompletedState(s)).length} {t('overview.completedTasks', { defaultValue: 'Tareas completadas' })}
              </Badge>
            </div>
          )}
        </div>
      </div>

      {/* Contenedor del contenido: solo se renderiza si hay children, así no queda espacio vacío */}
      {children != null && (
        <div
          className={`anima-configuracionoverview__content ${contentContainerClassName}`}
          style={{
            width: '100%',
            minWidth: 0,
            minHeight: 0,
            flex: '1 1 auto',
            paddingTop: '16px',
            paddingRight: isNarrow ? '16px' : '24px',
            paddingBottom: '24px',
            paddingLeft: isNarrow ? '16px' : '24px',
            opacity: 1,
            boxSizing: 'border-box',
            display: 'flex',
            flexDirection: 'column',
            gap: '24px',
            ...(contentContainerStyle || {}),
          }}
        >
          {children}
        </div>
      )}

      {/* Contenedor hijo fijo desde abajo: 424px alto, borde dashed */}
      <div
        className="anima-configuracionoverview__bottom-panel"
        style={{
          width: '100%',
          minWidth: 0,
          height: showIcons ? '424px' : 'auto',
          flexShrink: 0,
          margin: 0,
          paddingLeft: 'var(--space-16, 1rem)',
          paddingRight: 'var(--space-16, 1rem)',
          paddingTop: showIcons ? 0 : 'var(--space-16, 1rem)',
          paddingBottom: 'var(--space-16, 1rem)',
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
        }}
      >
        {[0, 1, 2, 3, 4].map((index) => {
          const estado = isCompletedState(slotStates[index]) ? completedState : 'Pendiente';
          const iconName = estado === completedState ? 'CheckCircleIcon' : 'EllipsisHorizontalCircleIcon';
          const iconStyle =
            estado === completedState
              ? {
                  flexShrink: 0,
                  fill: '#D3FFDF',
                  stroke: 'var(--misc-exito-info, #0A742C)',
                }
              : { flexShrink: 0, color: 'var(--color-grey-400, #919191)' };

          const handleSlotClick = () => {
            if (typeof onSlotStateChange === 'function') {
              const nuevoEstado = estado === completedState ? 'Pendiente' : completedState;
              onSlotStateChange(index, nuevoEstado);
            }
          };

          const handleKeyDown = (e) => {
            if (typeof onSlotStateChange === 'function' && (e.key === 'Enter' || e.key === ' ')) {
              e.preventDefault();
              handleSlotClick();
            }
          };

          const isClickable = typeof onSlotStateChange === 'function';
          const textColor =
            estado === completedState
              ? 'var(--color-cyan-19)'
              : 'var(--color-grey-600, #5F5F5F)';
          const titleText = slotTitles[index] ?? '';
          const subtitleText = slotSubtitles[index] ?? '';

          const titleTypographyStyle = {
            fontFamily: FONT_FAMILY_SANS,
            fontWeight: 500,
            fontStyle: 'normal',
            fontSize: '16px',
            lineHeight: '24px',
            letterSpacing: '0%',
            verticalAlign: 'middle',
            color: textColor,
            margin: 0,
          };
          const subtitleTypographyStyle = {
            fontFamily: FONT_FAMILY_SANS,
            fontWeight: 400,
            fontStyle: 'normal',
            fontSize: '16px',
            lineHeight: '24px',
            letterSpacing: '0%',
            verticalAlign: 'middle',
            color: textColor,
            margin: 0,
          };

          return (
            <div
              key={index}
              className="anima-configuracionoverview__bottom-panel-slot"
              style={{
                width: '100%',
                minHeight: showIcons ? '80px' : '116px',
                flexShrink: 0,
                boxSizing: 'border-box',
                display: 'flex',
                alignItems: showIcons ? 'center' : 'flex-start',
                justifyContent: 'center',
                ...(index < 4 ? { borderBottom: '1px solid #E5E5E5' } : {}),
              }}
            >
              <div
                className="anima-configuracionoverview__bottom-panel-slot-inner"
                role={isClickable ? 'button' : undefined}
                tabIndex={isClickable ? 0 : undefined}
                onClick={isClickable ? handleSlotClick : undefined}
                onKeyDown={isClickable ? handleKeyDown : undefined}
                style={{
                  width: '100%',
                  minHeight: showIcons ? '48px' : undefined,
                  height: showIcons ? undefined : 'auto',
                  flexShrink: 0,
                  boxSizing: 'border-box',
                  display: 'flex',
                  flexDirection: showIcons ? 'row' : 'column',
                  alignItems: showIcons ? 'center' : 'stretch',
                  alignSelf: 'stretch',
                  paddingLeft: showIcons ? '12px' : 0,
                  paddingTop: showIcons ? 0 : '12px',
                  paddingBottom: showIcons ? 0 : '12px',
                  gap: '12px',
                  ...(isClickable ? { cursor: 'pointer' } : {}),
                }}
              >
                {showIcons && <Icon name={iconName} size={24} style={iconStyle} />}
                <div
                  style={{
                    flex: showIcons ? '1 1 0' : '0 0 auto',
                    minWidth: 0,
                    minHeight: '48px',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: 0,
                  }}
                >
                  <div
                    className="anima-configuracionoverview__slot-inner-green"
                    style={{
                      width: '100%',
                      minHeight: '24px',
                      flexShrink: 0,
                      boxSizing: 'border-box',
                      display: 'flex',
                      alignItems: 'flex-start',
                      paddingRight: '12px',
                    }}
                  >
                    <Typography
                      component="span"
                      style={{
                        ...titleTypographyStyle,
                        wordBreak: 'break-word',
                        overflowWrap: 'break-word',
                        display: 'block',
                      }}
                    >
                      {titleText || '\u00A0'}
                    </Typography>
                  </div>
                  <div
                    className="anima-configuracionoverview__slot-inner-green"
                    style={{
                      width: '100%',
                      minHeight: '24px',
                      flexShrink: 0,
                      boxSizing: 'border-box',
                      display: 'flex',
                      alignItems: 'flex-start',
                      paddingRight: '12px',
                    }}
                  >
                    <Typography
                      component="span"
                      style={{
                        ...subtitleTypographyStyle,
                        wordBreak: 'break-word',
                        overflowWrap: 'break-word',
                        display: 'block',
                      }}
                    >
                      {subtitleText || '\u00A0'}
                    </Typography>
                  </div>
                </div>
                <div
                  style={{
                    flexShrink: 0,
                    height: '24px',
                    display: 'flex',
                    alignItems: 'center',
                    ...(!showIcons ? { marginTop: '8px' } : {}),
                  }}
                >
                  <Badge
                    variant={estado === completedState ? 'success' : 'danger'}
                    size="small"
                    className="anima-configuracionoverview__slot-badge"
                    style={{
                      width: '96px',
                      height: '24px',
                      opacity: 1,
                      borderRadius: 'var(--radius-16, 16px)',
                      borderWidth: '1px',
                      borderStyle: 'solid',
                      borderColor:
                        estado === completedState
                          ? 'var(--color-status-success, #0A742C)'
                          : 'var(--color-status-warning, #CC4908)',
                      paddingTop: '2px',
                      paddingRight: '12px',
                      paddingBottom: '4px',
                      paddingLeft: '12px',
                      backgroundColor:
                        estado === completedState
                          ? 'var(--misc-exito-fondo, #D3FFDF)'
                          : 'var(--color-neutrals-white, #FFFFFF)',
                      fontFamily: FONT_FAMILY_MONO,
                      fontWeight: 400,
                      fontStyle: 'normal',
                      fontSize: '12px',
                      lineHeight: '18px',
                      letterSpacing: '0%',
                      textAlign: estado === completedState ? 'right' : 'center',
                      verticalAlign: 'middle',
                      color:
                        estado === completedState
                          ? 'var(--color-status-success, #0A742C)'
                          : 'var(--color-status-warning, #CC4908)',
                      display: 'inline-flex',
                      alignItems: 'center',
                      justifyContent: estado === completedState ? 'flex-end' : 'center',
                      boxSizing: 'border-box',
                    }}
                  >
                    {estado === completedState ? completedState : 'Pendiente'}
                  </Badge>
                </div>
              </div>
            </div>
          );
        })}
      </div>
      </div>
    </div>
  );
};

export default ConfiguracionOverview;
