import { Layout, Menu } from 'antd';
import {
  DashboardOutlined,
  BookOutlined,
  BankOutlined,
  AccountBookOutlined,
  PercentageOutlined,
  TeamOutlined,
  SettingOutlined,
  FileTextOutlined,
  UserOutlined,
  BuildOutlined,
  ShopOutlined,
  ShoppingOutlined,
  ShoppingCartOutlined,
  FileDoneOutlined,
  FileExclamationOutlined,
  ExportOutlined,
} from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { useUIStore } from '@/stores/uiStore';
import type { MenuProps } from 'antd';

const { Sider } = Layout;

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: string,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

const menuItems: MenuItem[] = [
  getItem('Dashboard', '/', <DashboardOutlined />),

  getItem('Bogfoering', 'accounting', <BookOutlined />, [
    getItem('Kassekladde', '/kassekladde', <FileTextOutlined />),
    getItem('Kontooversigt', '/kontooversigt', <AccountBookOutlined />),
  ]),

  getItem('Fakturering', 'invoicing', <FileDoneOutlined />, [
    getItem('Kunder', '/kunder', <ShopOutlined />),
    getItem('Produkter', '/produkter', <ShoppingOutlined />),
    getItem('Ordrer', '/ordrer', <ShoppingCartOutlined />),
    getItem('Fakturaer', '/fakturaer', <FileDoneOutlined />),
    getItem('Kreditnotaer', '/kreditnotaer', <FileExclamationOutlined />),
  ]),

  getItem('Bank', 'bank', <BankOutlined />, [
    getItem('Bankafstemning', '/bankafstemning', <BankOutlined />),
  ]),

  getItem('Rapportering', 'reporting', <PercentageOutlined />, [
    getItem('Momsindberetning', '/momsindberetning', <PercentageOutlined />),
    getItem('Loenforstaelse', '/loenforstaelse', <TeamOutlined />),
    getItem('Eksport', '/eksport', <ExportOutlined />),
  ]),

  getItem('Indstillinger', 'settings', <SettingOutlined />, [
    getItem('Virksomhed', '/indstillinger', <BuildOutlined />),
    getItem('Min profil', '/profil', <UserOutlined />),
  ]),
];

// Determine open keys for submenus based on current path
function getOpenKeys(pathname: string): string[] {
  if (pathname === '/kassekladde' || pathname === '/kontooversigt') {
    return ['accounting'];
  }
  if (pathname === '/kunder' || pathname === '/produkter' || pathname === '/ordrer' || pathname === '/fakturaer' || pathname === '/kreditnotaer') {
    return ['invoicing'];
  }
  if (pathname === '/bankafstemning') {
    return ['bank'];
  }
  if (pathname === '/momsindberetning' || pathname === '/loenforstaelse' || pathname === '/eksport') {
    return ['reporting'];
  }
  if (pathname === '/indstillinger' || pathname === '/profil') {
    return ['settings'];
  }
  return [];
}

// Exported menu component for reuse in mobile Drawer
interface SidebarMenuProps {
  onNavigate?: () => void;
}

export function SidebarMenu({ onNavigate }: SidebarMenuProps) {
  const navigate = useNavigate();
  const location = useLocation();

  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    if (key.startsWith('/')) {
      navigate(key);
      onNavigate?.();
    }
  };

  const selectedKeys = [location.pathname];

  return (
    <Menu
      theme="dark"
      mode="inline"
      selectedKeys={selectedKeys}
      defaultOpenKeys={getOpenKeys(location.pathname)}
      items={menuItems}
      onClick={handleMenuClick}
      style={{ borderRight: 0 }}
    />
  );
}

export default function Sidebar() {
  const { sidebarCollapsed, toggleSidebar } = useUIStore();

  return (
    <Sider
      collapsible
      collapsed={sidebarCollapsed}
      onCollapse={toggleSidebar}
      width={220}
      style={{
        overflow: 'auto',
        height: '100vh',
        position: 'fixed',
        left: 0,
        top: 0,
        bottom: 0,
        zIndex: 100,
      }}
    >
      {/* Logo */}
      <div
        style={{
          height: 64,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
        }}
      >
        <span
          style={{
            color: '#fff',
            fontSize: sidebarCollapsed ? 16 : 18,
            fontWeight: 600,
            whiteSpace: 'nowrap',
          }}
        >
          {sidebarCollapsed ? 'B' : 'Books'}
        </span>
      </div>

      {/* Navigation Menu */}
      <SidebarMenu />
    </Sider>
  );
}
