import { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Icon } from '../../Atoms/Icon/Icon';
import { Avatar } from '../../Atoms/Avatar/Avatar';
import { Typography } from '../../Atoms/Typography/Typography';
import { SidebarPointMobile } from '../Sidebar/SidebarPoint';
import { DesplegablePerfil } from '../DesplegablePerfil/DesplegablePerfil';
import { SaludoConFechaDashboard } from '../SaludoConFechaDashboard/SaludoConFechaDashboard';
import { FONT_FAMILY_SANS } from '../../../designTokens';

// Constantes de diseño reutilizables
const HEADER_HEIGHT = '80px';
const SEARCH_INPUT_HEIGHT = '40px';
const SEARCH_ICON_SIZE = '40px';
const NOTIFICATION_BADGE_COLOR = '#6D3856';
const TEXT_COLOR_GRAY_700 = '#374151';
const BORDER_COLOR_GRAY_400 = '#9ca3af';
const FOCUS_BORDER_COLOR = '#3b82f6';

// Constantes de tipografía
const FONT_WEIGHT_REGULAR = 400;
const FONT_SIZE_BASE = '14px';
const LINE_HEIGHT_BASE = '20px';

// Constantes de breakpoints (solo tablet; mobile/desktop usan prop)
const BREAKPOINT_TABLET_MAX = '700px';
/** BASE/LG: mostrar nombre de usuario en desktop */
const BREAKPOINT_DESKTOP_USER_NAME_MIN_PX = 1440;

// Constantes de valores por defecto
const DEFAULT_MOBILE_BACKGROUND = 'transparent';
/** Separación entre la fila "Point" y SaludoConFechaDashboard en layout mobile (≤ mobileBreakpointPx; SM/MD por debajo de 1440px en diseño). */
const MOBILE_SALUDO_MARGIN_TOP_BELOW_POINT = '1rem';

export const HeaderPoint = ({
  /** Ancho en px: por debajo o igual se muestra la versión mobile */
  mobileBreakpointPx = 1024,
  searchPlaceholder,
  userName,
  userAvatar,
  notificationCount = 0,
  onSearch,
  onNotificationClick,
  onUserClick,
  onProfileClick,
  onSettingsClick,
  onLogoutClick,
  sidebarSections,
  sidebarActiveItem,
  onSidebarItemClick,
  sidebarItemBadges,
  sidebarCompanyName,
  sidebarCompanyLogo,
  /** Misma prop que SidebarPoint (desktop): imagen para logo/branding. En desktop va al sidebar lateral (160px); en mobile se pasa al menú hamburguesa (128px). */
  headerImageClient,
  mobileBackgroundColor = DEFAULT_MOBILE_BACKGROUND,
  /** Solo layout mobile (≤ mobileBreakpointPx): saludo sobre el buscador (fecha oculta por defecto) */
  saludoDate,
  /** Tono de texto del saludo en mobile: 'dark' | 'light' */
  saludoTextTone = 'light',
  /** Props extra para SaludoConFechaDashboard en mobile (saludo, prefijo/sufijo y locale se fijan desde i18n en el header) */
  saludoConFechaDashboardProps,
  className = '',
  ...props
}) => {
  const { t, i18n } = useTranslation();
  const resolvedSearchPlaceholder = searchPlaceholder ?? t('point.header.searchPlaceholder');

  const [searchValue, setSearchValue] = useState('');
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [isProfileDropdownOpen, setIsProfileDropdownOpen] = useState(false);
  const profileButtonRef = useRef(null);

  const handleSearchChange = (e) => {
    const value = e.target.value;
    setSearchValue(value);
    if (onSearch) {
      onSearch(value);
    }
  };

  const handleSearchSubmit = (e) => {
    e.preventDefault();
    if (onSearch) {
      onSearch(searchValue);
    }
  };

  const handleSidebarItemClick = (itemId) => {
    if (onSidebarItemClick) {
      onSidebarItemClick(itemId);
    }
    setIsSidebarOpen(false);
  };

  const handleCloseSidebar = () => {
    setIsSidebarOpen(false);
  };

  const handleToggleProfileDropdown = () => {
    setIsProfileDropdownOpen((prev) => {
      const newState = !prev;
      // Si hay un callback onUserClick, también lo ejecutamos para mantener compatibilidad
      if (onUserClick && !newState) {
        onUserClick();
      }
      return newState;
    });
  };

  const handleCloseProfileDropdown = () => {
    setIsProfileDropdownOpen(false);
  };

  const formatNotificationCount = (count) => {
    return count > 9 ? '9+' : count;
  };

  return (
    <>
      <style>{`
        .header-point-container {
          height: ${HEADER_HEIGHT};
        }
        .header-search-input {
          border-color: ${BORDER_COLOR_GRAY_400};
          height: ${SEARCH_INPUT_HEIGHT};
          color: ${TEXT_COLOR_GRAY_700};
          font-family: ${FONT_FAMILY_SANS};
          font-weight: ${FONT_WEIGHT_REGULAR};
          font-style: italic;
          font-size: ${FONT_SIZE_BASE};
          line-height: ${LINE_HEIGHT_BASE};
          letter-spacing: 0px;
        }
        .header-search-input::placeholder {
          color: ${BORDER_COLOR_GRAY_400} !important;
          opacity: 1 !important;
        }
        .header-search-icon-container {
          border-color: ${BORDER_COLOR_GRAY_400};
          border-left-color: transparent;
          width: ${SEARCH_ICON_SIZE};
          height: ${SEARCH_ICON_SIZE};
        }
        .header-search-form:focus-within .header-search-input {
          border-color: ${FOCUS_BORDER_COLOR} !important;
          box-shadow: 0 0 0 1px ${FOCUS_BORDER_COLOR};
        }
        .header-search-form:focus-within .header-search-icon-container {
          border-color: ${FOCUS_BORDER_COLOR} !important;
          border-left-color: transparent !important;
          box-shadow: 0 0 0 1px ${FOCUS_BORDER_COLOR};
        }
        .header-notification-badge {
          background-color: ${NOTIFICATION_BADGE_COLOR};
          border-radius: 12px;
        }
        .header-desktop-layout {
          height: ${HEADER_HEIGHT};
        }
        .header-search-wrapper {
          flex: 1 1 0%;
          min-width: 0;
        }
        .header-actions-wrapper {
          flex-shrink: 0;
        }
        .header-desktop-user-name {
          display: none;
        }
        /* Estilos para rango intermedio (1025px - 700px) - No aplica con nuevo breakpoint */
        @media (min-width: ${mobileBreakpointPx + 1}px) and (max-width: ${BREAKPOINT_TABLET_MAX}) {
          .header-desktop-layout {
            gap: 0.5rem;
            padding-left: 0.25rem;
            padding-right: 0.25rem;
          }
          .header-actions-wrapper {
            gap: 0.5rem;
            flex-shrink: 0;
          }
          .header-actions-wrapper button {
            padding: 0.375rem;
          }
        }
        @media (max-width: ${mobileBreakpointPx}px) {
          header.header-point-mobile,
          .header-point-mobile,
          header.bg-white.header-point-mobile {
            background-color: transparent !important;
            background: transparent !important;
            border-bottom: none !important;
            width: 100% !important;
            max-width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
            left: 0 !important;
            right: 0 !important;
          }
          header.header-point-mobile[style*="background"],
          .header-point-mobile[style*="background"],
          header.header-point-mobile[style*="backgroundColor"] {
            background-color: transparent !important;
            background: transparent !important;
          }
          header.header-point-mobile > div {
            width: 100% !important;
            max-width: 100% !important;
            padding-left: 0 !important;
            padding-right: 0 !important;
            margin: 0 !important;
          }
          .header-mobile-layout {
            display: block !important;
            position: relative !important;
            width: 100% !important;
            max-width: 100% !important;
          }
          .header-mobile-top-row {
            display: flex !important;
            align-items: center !important;
            justify-content: space-between !important;
            padding: 8px 4px !important;
            min-height: 48px !important;
            width: 100% !important;
            max-width: 100% !important;
            box-sizing: border-box !important;
          }
          .header-mobile-menu-button,
          .header-mobile-notification-button {
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
          }
          .header-mobile-point-text {
            display: flex !important;
            align-items: center !important;
            color: #ffffff !important;
          }
          .header-mobile-layout::after {
            content: '' !important;
            position: absolute !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            width: 100% !important;
            height: calc(48px + ${MOBILE_SALUDO_MARGIN_TOP_BELOW_POINT} + 72px + 12px + 8px + 40px) !important;
            background-color: ${mobileBackgroundColor} !important;
            background: ${mobileBackgroundColor} !important;
            z-index: 0 !important;
            border-bottom: ${mobileBackgroundColor !== DEFAULT_MOBILE_BACKGROUND ? '1px solid var(--color-main-800)' : 'none'} !important;
            pointer-events: none !important;
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
          }
          .header-mobile-top-row {
            position: relative;
            z-index: 2 !important;
          }
          /* Saludo (sin fecha): solo mobile, centrado sobre el buscador */
          .header-mobile-saludo-row {
            position: relative;
            z-index: 2 !important;
            width: 100%;
            min-width: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            box-sizing: border-box;
            margin-top: ${MOBILE_SALUDO_MARGIN_TOP_BELOW_POINT};
            padding: 8px 4px 4px;
          }
          /* Saludo “Hola” desactiva el centrado interno del componente; aquí forzamos centro real */
          .header-mobile-saludo-row > div.w-full > .grid {
            padding-left: 0 !important;
            padding-right: 0 !important;
            justify-items: center !important;
          }
          .header-mobile-saludo-row .scfd-saludo-fecha {
            width: 100%;
            max-width: 100%;
            align-items: center !important;
            justify-content: center !important;
          }
          .header-mobile-saludo-row .scfd-greeting-wrapper {
            width: 100% !important;
            display: flex !important;
            justify-content: center !important;
            align-items: center !important;
          }
          .header-mobile-saludo-row .scfd-greeting {
            text-align: center !important;
            width: 100%;
          }
          .header-mobile-search-row {
            position: relative;
            z-index: 2 !important;
            display: block;
            padding: 12px 4px 8px 4px !important;
            width: 100% !important;
            max-width: 100% !important;
            box-sizing: border-box !important;
          }
          .header-desktop-layout {
            display: none !important;
          }
          .header-mobile-layout .header-search-input {
            font-size: 12px !important;
            padding-left: 12px !important;
            padding-right: 12px !important;
            height: 40px !important;
          }
          .header-mobile-layout .header-search-icon-container {
            width: 36px !important;
            height: 40px !important;
          }
          .header-mobile-menu-icon {
            color: var(--color-neutrals-white) !important;
          }
          .header-mobile-notification-icon {
            color: var(--color-neutrals-white) !important;
          }
          /* Cambiar color de iconos cuando los botones tienen hover/active/focus */
          .header-mobile-menu-button:hover .header-mobile-menu-icon,
          .header-mobile-menu-button:active .header-mobile-menu-icon,
          .header-mobile-menu-button:focus .header-mobile-menu-icon {
            color: ${TEXT_COLOR_GRAY_700} !important;
          }
          .header-mobile-notification-button:hover .header-mobile-notification-icon,
          .header-mobile-notification-button:active .header-mobile-notification-icon,
          .header-mobile-notification-button:focus .header-mobile-notification-icon {
            color: ${TEXT_COLOR_GRAY_700} !important;
          }
        }
        @media (min-width: ${mobileBreakpointPx + 1}px) {
          .header-mobile-layout {
            display: none;
          }
          .header-desktop-user-name {
            display: none !important;
          }
          header.header-point-mobile {
            border-bottom: none !important;
          }
        }
        @media (min-width: ${BREAKPOINT_DESKTOP_USER_NAME_MIN_PX}px) {
          .header-desktop-user-name {
            display: block !important;
          }
        }
      `}</style>
      
      <header
        className={`bg-white header-point-mobile rounded-12 header-point-container ${className}`}
        {...props}
      >
        <div className="w-full" style={{ paddingLeft: '4px', paddingRight: '4px' }}>
          {/* Layout Desktop (más de 1364px) */}
          <div className="header-desktop-layout flex items-center justify-between" style={{ height: HEADER_HEIGHT, padding: '16px' }}>
            {/* Barra de búsqueda con icono a la derecha */}
            <div className="header-search-wrapper" style={{ marginRight: '16px' }}>
              <form onSubmit={handleSearchSubmit} className="header-search-form flex items-center w-full">
                <input
                  type="text"
                  value={searchValue}
                  onChange={handleSearchChange}
                  placeholder={resolvedSearchPlaceholder}
                  aria-label={resolvedSearchPlaceholder}
                  className="header-search-input flex-1 pl-2 md:pl-4 pr-2 md:pr-4 py-2 md:py-2.5 bg-white border border-gray-400 rounded-l-lg focus:outline-none text-sm md:text-base"
                  style={{ 
                    height: '40px', 
                    borderRight: 'none', 
                    borderTopRightRadius: '0', 
                    borderBottomRightRadius: '0',
                    color: '#374151',
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 400,
                    fontStyle: 'italic',
                    fontSize: '14px',
                    lineHeight: '20px',
                    letterSpacing: '0px'
                  }}
                />
                
                <div className="header-search-icon-container flex items-center justify-center border border-gray-400 rounded-r-lg bg-white" style={{
                  width: '40px',
                  height: '40px',
                  borderTopLeftRadius: '0',
                  borderBottomLeftRadius: '0',
                }}>
                  <Icon 
                    name="MagnifyingGlassIcon" 
                    variant="24-outline" 
                    size={20} 
                    className="color-gray-600" 
                  />
                </div>
              </form>
            </div>

            {/* Notificaciones y Perfil */}
            <div className="header-actions-wrapper flex items-center space-x-3 md:space-x-6 flex-shrink-0" style={{ marginLeft: 'auto', paddingRight: '0px' }}>
              {notificationCount !== undefined && (
                <button
                  onClick={onNotificationClick}
                  className="ml-3 p-2 hover:bg-gray-100 rounded-lg transition-colors flex items-center gap-2"
                  aria-label={t('header.notificationsAria')}
                  style={{ transform: 'translateX(12px)' }}
                >
                  <span
                    className="relative inline-block"
                    style={{
                      width: '24px',
                      height: '24px',
                      opacity: 1,
                    }}
                  >
                    <Icon 
                      name="BellIcon" 
                      variant="24-outline" 
                      size={24} 
                      className="color-gray-600"
                      style={{
                        width: '24px',
                        height: '24px',
                        position: 'absolute',
                        top: '0px',
                        left: '0px',
                        opacity: 1,
                        transform: 'rotate(0deg)',
                      }} 
                    />
                  </span>
                  {notificationCount > 0 && (
                    <span className="h-5 text-white flex items-center justify-center text-body-sm-14 font-medium header-notification-badge" style={{
                      minWidth: '24px',
                      width: 'fit-content',
                      height: '20px',
                      paddingTop: '2px',
                      paddingRight: '8px',
                      paddingBottom: '2px',
                      paddingLeft: '8px',
                      borderRadius: '16px',
                      opacity: 1,
                      transform: 'rotate(0deg)',
                    }}>
                      {formatNotificationCount(notificationCount)}
                    </span>
                  )}
                </button>
              )}

              {(userName || userAvatar) && (
                <div className="relative">
                  <button
                    ref={profileButtonRef}
                    onClick={handleToggleProfileDropdown}
                    className="flex items-center gap-2 hover:bg-gray-50 rounded-lg px-2 py-1.5 transition-colors cursor-pointer"
                    aria-label={t('header.profileAria')}
                    aria-expanded={isProfileDropdownOpen}
                  >
                    <Avatar
                      src={userAvatar}
                      name={userName}
                      size="medium"
                      variant="circle"
                      className="cursor-pointer"
                      style={{
                        width: '36px',
                        height: '36px',
                        opacity: 1,
                        borderRadius: '16777200px',
                        transform: 'rotate(0deg)',
                      }}
                    />
                    {userName ? (
                      <Typography
                        variant="body-lg"
                        className="header-desktop-user-name color-gray-700 hidden md:block cursor-pointer"
                        style={{
                          fontFamily: FONT_FAMILY_SANS,
                          fontWeight: 400,
                          fontStyle: 'normal',
                          fontSize: '16px',
                          lineHeight: '24px',
                          letterSpacing: '0%',
                          verticalAlign: 'middle',
                        }}
                      >
                        {userName}
                      </Typography>
                    ) : null}
                    <Icon
                      name="ChevronDownIcon"
                      variant="24-outline"
                      size={20}
                      className="color-gray-500 transition-transform duration-200 cursor-pointer"
                      style={{
                        transform: isProfileDropdownOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                      }}
                    />
                  </button>
                  <DesplegablePerfil
                    isOpen={isProfileDropdownOpen}
                    onClose={handleCloseProfileDropdown}
                    onProfileClick={onProfileClick}
                    onSettingsClick={onSettingsClick}
                    onLogoutClick={onLogoutClick}
                    triggerRef={profileButtonRef}
                  />
                </div>
              )}
            </div>
          </div>

          {/* Layout Mobile (480px o menos) */}
          <div className="header-mobile-layout">
            {/* Primera fila: Menú, Point (centrado), Notificaciones */}
            <div className="header-mobile-top-row relative">
              {/* Lado izquierdo: Menú hamburguesa */}
              <div className="flex items-center">
                <button
                  onClick={() => setIsSidebarOpen(true)}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors header-mobile-menu-button cursor-pointer"
                  aria-label={t('header.menuAria')}
                >
                  <Icon 
                    name="Bars3Icon" 
                    variant="24-outline" 
                    size={24} 
                    className="header-mobile-menu-icon" 
                  />
                </button>
              </div>

              {/* Centro: Texto "Point" */}
              <div className="absolute left-1/2 -translate-x-1/2 flex items-center h-full">
                <Typography
                  variant="body-md"
                  className="header-mobile-point-text"
                  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>
              </div>

              {/* Lado derecho: Notificaciones */}
              <div className="flex items-center ml-auto">
                {notificationCount !== undefined && (
                  <button
                    onClick={onNotificationClick}
                    className="relative p-2 hover:bg-gray-100 rounded-lg transition-colors header-mobile-notification-button cursor-pointer"
                    aria-label={t('header.notificationsAria')}
                  >
                    <Icon 
                      name="BellIcon" 
                      variant="24-outline" 
                      size={24} 
                      className="header-mobile-notification-icon" 
                    />
                    {notificationCount > 0 && (
                      <span className="absolute -top-1 -right-1 px-1.5 py-0.5 min-w-[20px] h-5 text-white rounded-full flex items-center justify-center text-body-sm-14 font-medium header-notification-badge">
                        {formatNotificationCount(notificationCount)}
                      </span>
                    )}
                  </button>
                )}
              </div>
            </div>

            {/* SM/MD (≤ mobileBreakpointPx): solo saludo centrado sobre el buscador */}
            <div className="header-mobile-saludo-row">
              <SaludoConFechaDashboard
                key={i18n.language}
                userName={userName}
                date={saludoDate ?? new Date()}
                showInicio={false}
                textTone={saludoTextTone}
                mobileBreakpointPx={mobileBreakpointPx}
                responsiveBreakpointPx={mobileBreakpointPx}
                {...(saludoConFechaDashboardProps || {})}
                locale={i18n.language}
                saludo={t('saludo.hola')}
                greetingPrefix={t('saludo.greetingPrefix')}
                greetingSuffix={t('saludo.greetingSuffix')}
                showDate={false}
              />
            </div>

            {/* Fila de búsqueda */}
            <div className="header-mobile-search-row">
              <form onSubmit={handleSearchSubmit} className="header-search-form flex items-center w-full">
                <input
                  type="text"
                  value={searchValue}
                  onChange={handleSearchChange}
                  placeholder={resolvedSearchPlaceholder}
                  className="header-search-input flex-1 pl-3 pr-3 py-2 bg-white border border-gray-400 focus:outline-none text-sm"
                  style={{ 
                    height: '40px', 
                    borderRight: 'none', 
                    borderTopLeftRadius: '24px',
                    borderBottomLeftRadius: '24px',
                    borderTopRightRadius: '0', 
                    borderBottomRightRadius: '0',
                    color: '#374151',
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 400,
                    fontStyle: 'italic',
                    fontSize: '14px',
                    lineHeight: '20px',
                    letterSpacing: '0px'
                  }}
                />
                
                <div className="header-search-icon-container flex items-center justify-center border border-gray-400 bg-white" style={{ 
                  width: '36px', 
                  height: '40px',
                  borderTopLeftRadius: '0',
                  borderBottomLeftRadius: '0',
                  borderTopRightRadius: '24px',
                  borderBottomRightRadius: '24px'
                }}>
                  <Icon 
                    name="MagnifyingGlassIcon" 
                    variant="24-outline" 
                    size={20} 
                    className="color-gray-600" 
                  />
                </div>
              </form>
            </div>
          </div>
        </div>

        {/* SidebarPointMobile - Solo visible en móvil cuando está abierto */}
        {isSidebarOpen && (
          <div className="header-mobile-sidebar-wrapper">
            <SidebarPointMobile
              sections={sidebarSections}
              activeItem={sidebarActiveItem}
              onItemClick={handleSidebarItemClick}
              itemBadges={sidebarItemBadges}
              headerImageClient={headerImageClient}
              companyName={sidebarCompanyName}
              companyLogo={sidebarCompanyLogo}
              isOpen={isSidebarOpen}
              onClose={handleCloseSidebar}
            />
          </div>
        )}
      </header>
    </>
  );
};

export default HeaderPoint;
