import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Settings, LogOut } from 'lucide-react';
import { TopNav, TopNavHeading } from '@astryxdesign/core/TopNav';
import { DropdownMenu } from '@astryxdesign/core/DropdownMenu';

import Logo from '@/components/Logo';
import UserAvatar from '@/components/UserAvatar';
import { fetchUsers } from '@/utils/apiClient';

export default function Header({ isSidebarCollapsed }) {
  const navigate = useNavigate();

  let storedUserObj = { name: 'Admin', role: 'Operations Admin', id: 0 };
  try {
    const storedUser = localStorage.getItem('user');
    if (storedUser) storedUserObj = JSON.parse(storedUser);
  } catch (e) { }

  const [activeUserName, setActiveUserName] = useState(storedUserObj.name || 'Admin');

  useEffect(() => {
    fetchUsers().then((users) => {
      if (storedUserObj.email) {
        const matchingUser = users.find(u => u.email === storedUserObj.email);
        if (matchingUser && matchingUser.first_name) {
          setActiveUserName(matchingUser.first_name);
          localStorage.setItem('user', JSON.stringify({ ...storedUserObj, name: matchingUser.first_name }));
        }
      }
    }).catch(console.error);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <TopNav
      label="Main navigation"
      style={{
        backgroundColor: '#ffffff',
        borderBottom: '1px solid rgba(5, 54, 89, 0.08)',
        boxShadow: '0 1px 3px rgba(15, 23, 42, 0.04)'
      }}
      heading={
        <TopNavHeading
          logo={
            <Logo
              compact={isSidebarCollapsed}
              size={isSidebarCollapsed ? 36 : 32}
              height={28}
              // Scaling visually enlarges the mark without growing its layout
              // box, so the navbar row keeps its original width/height instead
              // of stretching taller every time the logo gets bigger.
              style={isSidebarCollapsed ? { transform: 'scale(1.4)' } : undefined}
            />
          }
          headingHref="/dashboard"
        />
      }
      endContent={
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <DropdownMenu
            button={{
              variant: 'ghost',
              size: 'lg',
              icon: <UserAvatar name={activeUserName} size={22} />,
              label: activeUserName
            }}
            items={[
              { label: 'Settings', icon: Settings, onClick: () => navigate('/settings') },
              { type: 'divider' },
              {
                label: 'Logout',
                icon: LogOut,
                onClick: () => { localStorage.removeItem('auth_token'); navigate('/login'); }
              }
            ]}
          />
        </div>
      }
    />
  );
}
