import { useState } from 'react';
import { Layout, Space, Button, Dropdown, Avatar, Divider, Tooltip, Badge } from 'antd';
import {
  UserOutlined,
  LogoutOutlined,
  SettingOutlined,
  BellOutlined,
  QuestionCircleOutlined,
  TeamOutlined,
  CrownOutlined,
  MenuOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { useNavigate } from 'react-router-dom';
import CompanySwitcher from './CompanySwitcher';
import FiscalYearSelector from './FiscalYearSelector';
import UserAccessManager from '@/components/company/UserAccessManager';
import { useAuthStore } from '@/stores/authStore';
import { useCanAdmin, useActiveCompanyRole } from '@/stores/companyStore';
import { useUIStore } from '@/stores/uiStore';
import { semanticColors, spacing } from '@/styles/designTokens';

const { Header: AntHeader } = Layout;

interface HeaderProps {
  isMobile?: boolean;
}

export default function Header({ isMobile = false }: HeaderProps) {
  const navigate = useNavigate();
  const { logout } = useAuthStore();
  const canAdmin = useCanAdmin();
  const activeRole = useActiveCompanyRole();
  const toggleMobileDrawer = useUIStore((state) => state.toggleMobileDrawer);
  const [userAccessOpen, setUserAccessOpen] = useState(false);

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: 'Min profil',
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: 'Indstillinger',
    },
    ...(canAdmin ? [{
      key: 'manage-users',
      icon: <TeamOutlined />,
      label: 'Administrer brugere',
    }] : []),
    {
      type: 'divider' as const,
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: 'Log ud',
      danger: true,
    },
  ];

  const handleUserMenuClick: MenuProps['onClick'] = ({ key }) => {
    switch (key) {
      case 'logout':
        logout();
        break;
      case 'settings':
        navigate('/indstillinger');
        break;
      case 'profile':
        navigate('/profil');
        break;
      case 'manage-users':
        setUserAccessOpen(true);
        break;
    }
  };

  return (
    <AntHeader
      style={{
        padding: `0 ${spacing.xl}px`,
        background: semanticColors.headerBg,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        borderBottom: `1px solid ${semanticColors.borderLight}`,
        position: 'sticky',
        top: 0,
        zIndex: 10,
      }}
    >
      {/* Left side - Mobile menu + Company Switcher and Fiscal Year Selector */}
      <Space size={isMobile ? 'small' : 'middle'}>
        {/* Hamburger menu for mobile */}
        {isMobile && (
          <Button
            type="text"
            icon={<MenuOutlined />}
            onClick={toggleMobileDrawer}
            aria-label="Åbn navigation"
            style={{ marginRight: spacing.xs }}
          />
        )}
        <Space split={!isMobile ? <Divider type="vertical" style={{ height: 24, margin: '0 8px' }} /> : undefined}>
          <CompanySwitcher compact={isMobile} />
          {!isMobile && <FiscalYearSelector />}
        </Space>
      </Space>

      {/* Right side - User actions */}
      <Space size="middle">
        {/* Team/User Management - only for owners */}
        {canAdmin && (
          <Tooltip title="Administrer brugere">
            <Button
              type="text"
              icon={<TeamOutlined />}
              onClick={() => setUserAccessOpen(true)}
              aria-label="Administrer brugere"
            />
          </Tooltip>
        )}

        {/* Help */}
        <Tooltip title="Hjælp">
          <Button
            type="text"
            icon={<QuestionCircleOutlined />}
            onClick={() => window.open('https://help.books.dk', '_blank')}
            aria-label="Hjælp"
          />
        </Tooltip>

        {/* Notifications */}
        <Tooltip title="Notifikationer">
          <Badge count={0} size="small">
            <Button
              type="text"
              icon={<BellOutlined />}
              onClick={() => navigate('/indstillinger')}
              aria-label="Notifikationer"
            />
          </Badge>
        </Tooltip>

        {/* User Menu */}
        <Dropdown
          menu={{
            items: userMenuItems,
            onClick: handleUserMenuClick,
          }}
          placement="bottomRight"
          trigger={['click']}
        >
          <Badge
            count={activeRole === 'owner' ? <CrownOutlined style={{ color: '#faad14', fontSize: 10 }} /> : 0}
            offset={[-2, 2]}
            style={{ cursor: 'pointer' }}
            role="button"
            aria-label="Brugermenu"
            aria-haspopup="menu"
            tabIndex={0}
          >
            <Avatar
              size="small"
              icon={<UserOutlined />}
              style={{ backgroundColor: '#1677ff' }}
              aria-hidden="true"
            />
          </Badge>
        </Dropdown>
      </Space>

      {/* User Access Manager Modal */}
      <UserAccessManager
        open={userAccessOpen}
        onClose={() => setUserAccessOpen(false)}
      />
    </AntHeader>
  );
}
