import { useState } from 'react';
import { Icon } from '../../Atoms/Icon/Icon';
import { Avatar } from '../../Atoms/Avatar/Avatar';
import { Typography } from '../../Atoms/Typography/Typography';
import { FONT_FAMILY_SANS } from '../../../designTokens';

// Constantes de diseño reutilizables
const NOTIFICATION_BADGE_COLOR = '#6D3856';

export const HeaderCompartido = ({
  searchPlaceholder = 'Buscar empleados, reportes, configuraciones...',
  userName,
  userAvatar,
  notificationCount = 0,
  onSearch,
  onNotificationClick,
  onUserClick,
  // Borde inferior (subrayado)
  showBottomBorder = false,
  bottomBorderClassName = 'border-b border-gray-200',
  // Overrides de estilo/clases para poder ajustar layout desde el proyecto consumidor
  desktopLayoutClassName = '',
  desktopLayoutStyle,
  desktopSearchContainerClassName = '',
  desktopSearchContainerStyle,
  className = '',
  ...props
}) => {
  const [searchValue, setSearchValue] = useState('');

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

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

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

  return (
    <header
      className={`bg-white ${showBottomBorder ? bottomBorderClassName : ''} ${className}`}
      {...props}
    >
      <style>{`
        .header-search-input {
          border-color: #9ca3af;
        }
        .header-search-input::placeholder {
          color: #9ca3af !important;
          opacity: 1 !important;
        }
        .header-search-icon-container {
          border-color: #9ca3af;
        }
        .header-search-form:focus-within .header-search-input {
          border-color: #3b82f6 !important;
          box-shadow: 0 0 0 1px #3b82f6;
        }
        .header-search-form:focus-within .header-search-icon-container {
          border-color: #3b82f6 !important;
          box-shadow: 0 0 0 1px #3b82f6;
        }
        .header-notification-badge {
          background-color: ${NOTIFICATION_BADGE_COLOR};
          border-radius: 12px;
        }
        .header-actions-wrapper {
          flex-shrink: 0;
        }
      `}</style>
      
      <div className="w-full" style={{ paddingLeft: '4px', paddingRight: '4px' }}>
        {/* Layout Desktop */}
        <div
          className={`header-desktop-layout flex items-center justify-between h-16 ${desktopLayoutClassName}`}
          style={desktopLayoutStyle}
        >
          {/* Barra de búsqueda con icono a la derecha */}
          <div
            className={`flex-1 mr-2 md:mr-4 ${desktopSearchContainerClassName}`}
            style={{ maxWidth: 'none', minWidth: '0', ...(desktopSearchContainerStyle || {}) }}
          >
            <form onSubmit={handleSearchSubmit} className="header-search-form flex items-center w-full">
              {/* Input de búsqueda */}
              <input
                type="text"
                value={searchValue}
                onChange={handleSearchChange}
                placeholder={searchPlaceholder}
                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'
                }}
              />
              
              {/* Recuadro con icono de buscar a la derecha */}
              <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 gap-3 md:gap-6">
            {notificationCount !== undefined && (
              <button
                onClick={onNotificationClick}
                className="relative p-2 hover:bg-gray-100 rounded-lg transition-colors"
                aria-label="Notificaciones"
              >
                <Icon 
                  name="BellIcon" 
                  variant="24-outline" 
                  size={24} 
                  className="color-gray-600" 
                />
                {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>
            )}

            {userName && (
              <button
                onClick={onUserClick}
                className="flex items-center gap-3 hover:bg-gray-50 rounded-lg px-2 py-1.5 transition-colors"
                aria-label="Perfil de usuario"
              >
                <Avatar
                  src={userAvatar}
                  name={userName}
                  size="medium"
                  variant="circle"
                />
                <Typography
                  variant="body-lg"
                  className="color-gray-700 hidden md:block header-user-name"
                >
                  {userName}
                </Typography>
                <Icon
                  name="ChevronDownIcon"
                  variant="24-outline"
                  size={20}
                  className="color-gray-500 header-user-chevron hidden md:block"
                />
              </button>
            )}
          </div>
        </div>
      </div>
    </header>
  );
};

export default HeaderCompartido;
