import { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Icon } from '../../Atoms/Icon/Icon';
import { Typography } from '../../Atoms/Typography/Typography';
import { LogoHexa } from '../../Atoms/LogoHexa/LogoHexa';
import { useViewportMaxWidth } from '../../../hooks/useViewportMaxWidth';
import { FONT_FAMILY_SANS } from '../../../designTokens';

function useDefaultSidebarSections() {
  const { t, i18n } = useTranslation();
  return useMemo(
    () => [
      {
        title: t('point.sidebar.section.people'),
        items: [
          { id: 'inicio', label: t('point.sidebar.item.home', { defaultValue: 'Inicio' }), icon: 'HomeIcon' },
          { id: 'empleados', label: t('point.sidebar.item.employees'), icon: 'UserGroupIcon' },
          { id: 'organizacion', label: t('point.sidebar.item.organization'), icon: 'BuildingOfficeIcon' },
        ],
      },
      {
        title: t('point.sidebar.section.talent'),
        items: [
          { id: 'reclutamiento', label: t('point.sidebar.item.recruitment'), icon: 'UserPlusIcon' },
          { id: 'desarrollo', label: t('point.sidebar.item.development'), icon: 'AcademicCapIcon' },
        ],
      },
    ],
    [t, i18n.language]
  );
}

/**
 * Lista plana de ítems de navegación. Inicio va en los datos (como el resto) o se antepone si el portal no lo envía.
 * Depende de `i18n.language` para que al cambiar idioma se recalculen las etiquetas aunque `t` conserve referencia.
 */
function useSidebarPointNavItems(resolvedSections, t, i18nLanguage) {
  return useMemo(() => {
    const flat = resolvedSections.flatMap((section) => section.items);
    if (flat.some((item) => item.id === 'inicio')) {
      return flat;
    }
    return [
      { id: 'inicio', label: t('point.sidebar.item.home', { defaultValue: 'Inicio' }), icon: 'HomeIcon' },
      ...flat,
    ];
  }, [resolvedSections, t, i18nLanguage]);
}

/** Locale BCP47 para fechas según idioma de i18next (alineado con Preferencias / portal). */
function getDateLocaleFromI18n(language) {
  if (language === 'pt-BR') return 'pt-BR';
  if (language === 'en-US' || language === 'en') return 'en-US';
  return 'es-AR';
}

export const SidebarPoint = ({
  /** Ancho en px: visible cuando viewport > breakpointPx, oculto cuando <= breakpointPx */
  breakpointPx = 1024,
  sections,
  activeItem,
  onItemClick,
  defaultCollapsed = false,
  /** Imagen opcional para bloque superior del sidebar (si llega, se muestra en un contenedor de 160px) */
  headerImageClient,
  companyName = 'HEXA Point',
  companyLogo,
  onCompanyClick,
  itemBadges = {}, // Objeto con { itemId: number } para los badges
  footerText, // Texto del footer: puede ser string "v1.0 | Powered by Nucleus" o objeto { version: "v1.0", poweredBy: "Powered by", brand: "Nucleus" }
  footerCollapsedContent, // Contenido a mostrar en el footer cuando está colapsado (puede ser string, ReactNode, o objeto con icon y text)
  Client = false, // Propiedad booleana para mostrar el logo de la empresa en la parte superior
  className = '',
  ...props
}) => {
  const defaultSections = useDefaultSidebarSections();
  const resolvedSections =
    sections != null && Array.isArray(sections) && sections.length > 0 ? sections : defaultSections;
  const { t, i18n } = useTranslation();
  const allNavItems = useSidebarPointNavItems(resolvedSections, t, i18n.language);
  const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
  const isViewportMobile = useViewportMaxWidth(breakpointPx);

  const toggleCollapse = () => {
    setIsCollapsed(!isCollapsed);
  };

  if (isViewportMobile) {
    return null;
  }

  return (
    <aside
      className={`bg-white transition-all duration-300 ease-in-out h-full rounded-16 ${
        isCollapsed ? 'w-20' : 'w-64'
      } ${className}`}
      style={{
        border: '1px solid #C4C4C4',
        borderRadius: '16px',
      }}
      {...props}
    >
      <nav className="h-full flex flex-col" style={{ overflow: 'hidden' }}>
        {headerImageClient ? (
          <div
            className="flex-shrink-0 flex items-center justify-center"
            style={{
              height: '160px',
              borderBottom: '1px solid #C4C4C4',
              padding: '16px',
              boxSizing: 'border-box',
            }}
          >
            <img
              src={headerImageClient}
              alt={t('point.sidebar.alt.headerLogo')}
              className="max-w-full max-h-full object-contain"
            />
          </div>
        ) : null}

        {/* Header con logo de empresa cuando Client es true - entre botón colapsar y botón Inicio */}
        {!headerImageClient && Client && companyLogo && !isCollapsed && (
          <div className="flex-shrink-0 border-b border-gray-200" style={{ borderStyle: 'dashed' }}>
            <div className="px-4 py-6 flex flex-col items-center justify-center">
              <img
                src={companyLogo}
                alt={companyName || t('point.sidebar.alt.companyLogo')}
                className="max-w-[200px] max-h-[80px] object-contain"
              />
            </div>
          </div>
        )}



        {/* Contenido del sidebar - Wrapper para controlar el espacio */}
        <div className="flex-1 min-h-0 flex flex-col overflow-hidden">
          <div
            className={`flex-1 overflow-y-auto ${isCollapsed ? 'py-2' : 'py-4'}`}
            style={{ overflowX: 'hidden', paddingBottom: '64px' }}
          >
          <div className="space-y-1">
          {allNavItems.map((item) => (
            <div key={item.id} className="px-4">
              <button
                type="button"
                onClick={() => onItemClick && onItemClick(item.id)}
                className={`w-full flex items-center cursor-pointer ${
                  isCollapsed ? 'justify-center px-2' : 'px-4 justify-between'
                } py-2.5 rounded-lg transition-all duration-200 ${
                  activeItem === item.id
                    ? ''
                    : 'color-gray-700 hover:bg-gray-100'
                }`}
                style={
                  activeItem === item.id
                    ? { backgroundColor: '#2D5C63' }
                    : {}
                }
                title={isCollapsed ? item.label : undefined}
              >
                <div className="flex items-center">
                  <Icon
                    name={item.icon}
                    variant="24-outline"
                    size={24}
                    className={`${isCollapsed ? '' : 'mr-3'} ${
                      activeItem === item.id ? 'color-white' : 'color-gray-700'
                    }`}
                  />
                  {!isCollapsed && (
                    <Typography
                      variant="body-lg"
                      weight={activeItem === item.id ? 'semibold' : 'regular'}
                      className={`${
                        activeItem === item.id ? 'color-white' : 'color-gray-700'
                      } min-w-0`}
                      style={{
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                      }}
                    >
                      {item.label}
                    </Typography>
                  )}
                </div>
                {!isCollapsed && ((itemBadges[item.id] !== undefined && itemBadges[item.id] > 0) || (item.id === 'empleados' && 2)) && (
                  <span
                    className="px-2 py-0.5 min-w-[20px] h-5 
                             rounded-full flex items-center justify-center
                             text-body-sm-14 font-medium flex-shrink-0"
                    style={{
                      backgroundColor: activeItem === item.id ? '#FFFFFF' : '#6D3856',
                      color: activeItem === item.id ? '#6D3856' : '#FFFFFF',
                      borderRadius: '12px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      lineHeight: '1',
                    }}
                  >
                    {item.id === 'empleados'
                      ? 2
                      : itemBadges[item.id] > 9
                        ? '9+'
                        : itemBadges[item.id]}
                  </span>
                )}
              </button>
            </div>
          ))}
          </div>
          </div>
        </div>

        {/* Footer con texto configurable - cuando está expandido */}
        {footerText && !isCollapsed && (
          <div className="px-4 pb-4 flex-shrink-0">
            <div 
              className="bg-white border rounded-lg px-3 py-2 flex items-center justify-center"
              style={{ 
                borderColor: '#2D5C63',
                borderRadius: '8px'
              }}
            >
              {typeof footerText === 'string' ? (
                <Typography
                  variant="body-sm"
                  style={{ color: '#2D5C63', fontSize: '14px', lineHeight: '20px' }}
                  className="text-center"
                >
                  {(() => {
                    const parts = footerText.split('|');
                    if (parts.length === 2) {
                      const leftPart = parts[0].trim();
                      const rightPart = parts[1].trim();
                      // Si contiene "Powered by", separar y poner la marca en bold
                      if (rightPart.includes('Powered by')) {
                        const poweredByMatch = rightPart.match(/Powered by (.+)/);
                        if (poweredByMatch) {
                          return (
                            <>
                              {leftPart} | Powered by <span className="font-bold">{poweredByMatch[1]}</span>
                            </>
                          );
                        }
                      }
                      return `${leftPart} | ${rightPart}`;
                    }
                    return footerText;
                  })()}
                </Typography>
              ) : (
                <Typography
                  variant="body-sm"
                  style={{ color: '#2D5C63', fontSize: '14px', lineHeight: '20px' }}
                  className="text-center"
                >
                  {footerText.version && `${footerText.version}`}
                  {footerText.version && (footerText.poweredBy || footerText.brand) && ' | '}
                  {footerText.poweredBy && `${footerText.poweredBy} `}
                  {footerText.brand && <span className="font-bold">{footerText.brand}</span>}
                </Typography>
              )}
            </div>
          </div>
        )}

        {/* Footer cuando está colapsado */}
        {footerCollapsedContent && isCollapsed && (
          <div className="px-1 pt-2 pb-2 flex justify-center flex-shrink-0" style={{ zIndex: 10 }}>
            <div 
              className="bg-white border rounded px-1 py-0.5 flex items-center justify-center"
              style={{ 
                borderColor: '#2D5C63',
                borderRadius: '4px',
                width: 'calc(100% - 8px)',
                minHeight: '20px'
              }}
            >
              {typeof footerCollapsedContent === 'string' ? (
                <span
                  style={{ 
                    color: '#2D5C63', 
                    fontSize: '9px', 
                    lineHeight: '1.2',
                    fontWeight: '600',
                    textAlign: 'center',
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    maxWidth: '100%'
                  }}
                >
                  {footerCollapsedContent}
                </span>
              ) : typeof footerCollapsedContent === 'object' && footerCollapsedContent.icon ? (
                <div className="flex items-center justify-center">
                  {footerCollapsedContent.icon && (
                    <Icon
                      name={footerCollapsedContent.icon}
                      variant="24-outline"
                      size={14}
                      style={{ color: '#2D5C63' }}
                    />
                  )}
                  {footerCollapsedContent.text && (
                    <span
                      style={{ 
                        color: '#2D5C63', 
                        fontSize: '10px',
                        marginLeft: footerCollapsedContent.icon ? '4px' : '0'
                      }}
                    >
                      {footerCollapsedContent.text}
                    </span>
                  )}
                </div>
              ) : (
                footerCollapsedContent
              )}
            </div>
          </div>
        )}
      </nav>
    </aside>
  );
};

/** Mismo radio que el panel `aside` del menú móvil (evita esquinas cuadradas en la cabecera verde). */
const SIDEBAR_POINT_MOBILE_BORDER_RADIUS = '16px';

// Componente SidebarPoint Mobile
const SidebarPointMobile = ({
  sections,
  activeItem,
  onItemClick,
  /** Imagen opcional para bloque entre fecha y menú en mobile (128px de alto) */
  headerImageClient,
  companyName = 'HEXA Point',
  companyLogo,
  onCompanyClick,
  itemBadges = {},
  isOpen: controlledIsOpen,
  onClose: controlledOnClose,
  className = '',
  ...props
}) => {
  const { t, i18n } = useTranslation();
  const defaultSections = useDefaultSidebarSections();
  const resolvedSections =
    sections != null && Array.isArray(sections) && sections.length > 0 ? sections : defaultSections;
  const allNavItems = useSidebarPointNavItems(resolvedSections, t, i18n.language);
  const [internalIsOpen, setInternalIsOpen] = useState(false);
  const [shouldAnimate, setShouldAnimate] = useState(false);
  
  // Si se proporciona control externo, usarlo; si no, usar estado interno
  const isMobileMenuOpen = controlledIsOpen !== undefined ? controlledIsOpen : internalIsOpen;
  const setIsMobileMenuOpen = controlledOnClose ? controlledOnClose : setInternalIsOpen;

  // Efecto para manejar la animación cuando se controla externamente
  useEffect(() => {
    if (controlledIsOpen !== undefined) {
      if (controlledIsOpen) {
        // Cuando se abre, primero montamos sin animación, luego activamos la animación
        setShouldAnimate(false);
        // Pequeño delay para asegurar que el DOM esté listo antes de animar
        const timer = setTimeout(() => {
          setShouldAnimate(true);
        }, 10);
        return () => clearTimeout(timer);
      } else {
        // Cuando se cierra, desactivamos la animación inmediatamente
        setShouldAnimate(false);
      }
    } else {
      setShouldAnimate(internalIsOpen);
    }
  }, [controlledIsOpen, internalIsOpen]);

  const toggleMobileMenu = () => {
    if (controlledOnClose) {
      controlledOnClose();
    } else {
      setInternalIsOpen(!internalIsOpen);
    }
  };

  const capitalizedDate = useMemo(() => {
    const dateLocale = getDateLocaleFromI18n(i18n.language);
    const formattedDate = new Date().toLocaleDateString(dateLocale, {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
    return formattedDate.charAt(0).toUpperCase() + formattedDate.slice(1);
  }, [i18n.language]);

  return (
    <>
      <style>{`
        .sidebar-point-mobile {
          width: 100%;
          max-width: 412px;
          transform: ${isMobileMenuOpen ? 'translateX(0)' : 'translateX(-100%)'};
          position: fixed;
          left: 0;
          top: 0;
          height: 100vh;
          z-index: 50;
          transition: ${shouldAnimate ? 'transform 0.3s ease-in-out' : 'none'};
        }
        .sidebar-point-mobile-overlay {
          position: fixed;
          inset: 0;
          background-color: rgba(0, 0, 0, 0.5);
          z-index: 40;
          transition: opacity 0.3s ease-in-out;
          opacity: ${isMobileMenuOpen ? '1' : '0'};
          pointer-events: ${isMobileMenuOpen ? 'auto' : 'none'};
        }
      `}</style>
      {/* Botón hamburguesa - solo visible cuando el menú está cerrado y no hay control externo */}
      {!isMobileMenuOpen && controlledIsOpen === undefined && (
        <button
          onClick={toggleMobileMenu}
          className="fixed top-4 left-4 z-50 p-2 bg-white rounded-lg 
                   hover:bg-gray-50 transition-colors"
          style={{ border: '1px solid #C4C4C4' }}
          aria-label={t('point.sidebar.aria.toggleMenu')}
        >
          <Icon
            name="Bars3Icon"
            variant="24-outline"
            size={24}
            className="color-gray-700"
          />
        </button>
      )}
      {/* Overlay para cerrar el menú */}
      <div
        className="sidebar-point-mobile-overlay"
        onClick={() => {
          if (controlledOnClose) {
            controlledOnClose();
          } else {
            toggleMobileMenu();
          }
        }}
      />
      <aside
        className={`bg-white sidebar-point-mobile ${className}`}
        style={{
          border: '1px solid #C4C4C4',
          borderRadius: SIDEBAR_POINT_MOBILE_BORDER_RADIUS,
          overflow: 'hidden',
        }}
        {...props}
      >
        <nav className="h-full flex flex-col">
          {/* Título de marca fijo (no i18n): siempre "Point" */}
          <div
            className="px-4 py-4 flex items-center justify-between flex-shrink-0"
            style={{
              backgroundColor: 'var(--color-main)',
              borderTopLeftRadius: SIDEBAR_POINT_MOBILE_BORDER_RADIUS,
              borderTopRightRadius: SIDEBAR_POINT_MOBILE_BORDER_RADIUS,
            }}
          >
            <Typography
              variant="body-md"
              style={{
                fontFamily: FONT_FAMILY_SANS,
                fontWeight: 400,
                fontStyle: 'normal',
                fontSize: '20px',
                lineHeight: '30px',
                letterSpacing: '0px',
                color: '#FFFFFF',
                leadingTrim: 'none',
                margin: 0,
                verticalAlign: 'middle',
              }}
            >
              Point
            </Typography>
            <button
              onClick={() => {
                if (controlledOnClose) {
                  controlledOnClose();
                } else {
                  toggleMobileMenu();
                }
              }}
              className="p-1 hover:bg-opacity-80 rounded transition-colors"
              style={{ cursor: 'pointer' }}
              aria-label={t('point.sidebar.aria.closeMenu')}
            >
              <Icon
                name="XMarkIcon"
                variant="24-outline"
                size={24}
                className="color-white"
              />
            </button>
          </div>
          {/* Sección gris con fecha */}
          <div className="bg-gray-100 px-4 py-3 border-b border-gray-200">
            <Typography
              variant="body-md"
              className="color-gray-700"
            >
              {capitalizedDate}
            </Typography>
          </div>
          {/* Bloque de imagen (si llega prop) entre fecha y menú */}
          {headerImageClient ? (
            <div
              className="bg-white flex items-center justify-center"
              style={{
                height: '128px',
                padding: '16px',
                boxSizing: 'border-box',
              }}
            >
              <img
                src={headerImageClient}
                alt={t('point.sidebar.alt.headerLogo')}
                className="max-w-full max-h-full object-contain"
              />
            </div>
          ) : null}
          {/* Logo de empresa (solo si se proporciona) */}
          {!headerImageClient && companyLogo && (
            <div className="bg-gray-100 px-4 py-6 flex justify-center border-b border-gray-200">
              <img
                src={companyLogo}
                alt={companyName || t('point.sidebar.alt.companyLogo')}
                className="max-w-[120px] max-h-[120px] object-contain"
              />
            </div>
          )}
          {/* Contenido del sidebar mobile: lista única (Inicio + ítems), misma construcción */}
          <div className="flex-1 overflow-y-auto py-4">
            <div className="space-y-1">
            {allNavItems.map((item) => (
              <div key={item.id} className="px-4">
                <button
                  type="button"
                  onClick={() => {
                    onItemClick && onItemClick(item.id);
                    toggleMobileMenu();
                  }}
                  className={`w-full flex items-center cursor-pointer px-4 justify-between py-2.5 rounded-lg transition-all duration-200 ${
                    activeItem === item.id
                      ? ''
                      : 'color-gray-700 hover:bg-gray-100'
                  }`}
                  style={
                    activeItem === item.id
                      ? { backgroundColor: '#2D5C63' }
                      : {}
                  }
                >
                  <div className="flex items-center">
                    <Icon
                      name={item.icon}
                      variant="24-outline"
                      size={24}
                      className={`mr-3 ${
                        activeItem === item.id ? 'color-white' : 'color-gray-700'
                      }`}
                    />
                    <Typography
                      variant="body-md"
                      weight={activeItem === item.id ? 'semibold' : 'regular'}
                      className={`${
                        activeItem === item.id ? 'color-white' : 'color-gray-700'
                      }`}
                      style={{ fontSize: '1rem' }}
                    >
                      {item.label}
                    </Typography>
                  </div>
                  {((itemBadges[item.id] !== undefined && itemBadges[item.id] > 0) || (item.id === 'empleados' && 2)) && (
                    <span
                      className="px-2 py-0.5 min-w-[20px] h-5 
                               rounded-full flex items-center justify-center
                               text-body-sm-14 font-medium flex-shrink-0"
                      style={{
                        backgroundColor: activeItem === item.id ? '#ffffff' : '#6D3856',
                        color: activeItem === item.id ? '#6D3856' : '#ffffff',
                        borderRadius: '12px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        lineHeight: '1',
                      }}
                    >
                      {item.id === 'empleados'
                      ? 2
                      : itemBadges[item.id] > 9
                        ? '9+'
                        : itemBadges[item.id]}
                    </span>
                  )}
                </button>
              </div>
            ))}
            </div>
          </div>
        </nav>
      </aside>
    </>
  );
};

// Exportar ambos componentes
export { SidebarPointMobile };
export default SidebarPoint;


