import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import ChangePasswordOverlay from './Users/ChangePasswordOverlay';
import NomenclatureManager from './NomenclatureManager/NomenclatureManager';
import './Header.css';

function Header() {
  const { currentUser, logout } = useAuth();
  const navigate = useNavigate();
  const [showPasswordOverlay, setShowPasswordOverlay] = useState(false);
  const [showNomenclatureManager, setShowNomenclatureManager] = useState(false);

  const getInitials = (user) => {
    if (user.first_name && user.last_name) {
      return `${user.first_name[0]}${user.last_name[0]}`.toUpperCase();
    }
    return user.username.substring(0, 2).toUpperCase();
  };

  const handleAvatarClick = () => {
    setShowPasswordOverlay(true);
  };

  return (
    <>
      <header className="app-header">
        <div className="header-content">
          <div className="header-left">
            {currentUser?.can_edit_documents && (
              <button
                className="nav-button"
                onClick={() => navigate('/report-editor')}
                title="Report Editor"
              >
                📝
              </button>
            )}
            {currentUser?.can_manage_entities && (
              <button
                className="nav-button"
                onClick={() => setShowNomenclatureManager(true)}
                title="Nomenclatures"
              >
                📋
              </button>
            )}
            {currentUser?.is_admin && (
              <button
                className="nav-button"
                onClick={() => navigate('/users')}
                title="User Manager"
              >
                👥
              </button>
            )}
            <h1>ScalesApp - Real-time Data Monitor</h1>
          </div>
          <div className="header-right">
            <div className="user-info">
              <span className="user-name">{currentUser?.username}</span>
              <span className="user-role">({currentUser?.role})</span>
            </div>
            <div className="avatar-container">
              <div className="avatar" onClick={handleAvatarClick} title="Change Password">
                {getInitials(currentUser || {})}
              </div>
              <button className="logout-button" onClick={logout} title="Logout">
                Logout
              </button>
            </div>
          </div>
        </div>
      </header>

      {showPasswordOverlay && (
        <ChangePasswordOverlay onClose={() => setShowPasswordOverlay(false)} />
      )}

      {showNomenclatureManager && (
        <NomenclatureManager onClose={() => setShowNomenclatureManager(false)} />
      )}
    </>
  );
}

export default Header;
