/**
 * KRA - Head Mode Layout
 * Top navigation layout with horizontal menu
 */
import React, { useState, useEffect, useMemo } from 'react';
import { Menu } from 'antd';
import type { MenuProps } from 'antd';
import { useModel, history, useLocation } from '@umijs/max';
import * as Icons from '@ant-design/icons';
import { useAsyncRouters } from '@/models';

interface MenuItem {
  name: string;
  path: string;
  hidden?: boolean;
  meta?: {
    title: string;
    icon?: string;
    activeName?: string;
  };
  children?: MenuItem[];
  parameters?: Array<{ type: string; key: string; value: string }>;
}

// Get icon component by name
const getIcon = (iconName?: string): React.ReactNode => {
  if (!iconName) return null;
  const IconComponent = (Icons as any)[iconName] || (Icons as any)[`${iconName}Outlined`];
  return IconComponent ? <IconComponent /> : null;
};

// Convert menu data to Ant Design menu items
const convertToMenuItems = (menus: MenuItem[]): MenuProps['items'] => {
  return menus
    .filter((item) => !item.hidden)
    .map((item) => {
      const hasChildren = item.children && item.children.filter((c) => !c.hidden).length > 0;

      if (hasChildren) {
        return {
          key: item.name,
          icon: getIcon(item.meta?.icon),
          label: item.meta?.title || item.name,
          children: convertToMenuItems(item.children!),
        };
      }

      return {
        key: item.name,
        icon: getIcon(item.meta?.icon),
        label: item.meta?.title || item.name,
      };
    });
};

interface HeadModeProps {
  /** Theme */
  theme?: 'light' | 'dark';
}

const HeadMode: React.FC<HeadModeProps> = ({ theme = 'light' }) => {
  const location = useLocation();
  const asyncRouters = useAsyncRouters();
  const { routeMap } = useModel('router');

  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);

  // Get menu items from async routers
  const menuItems = useMemo(() => {
    const rootMenu = asyncRouters?.[0];
    if (!rootMenu?.children) return [];
    return convertToMenuItems(rootMenu.children);
  }, [asyncRouters]);

  // Update selected keys based on current route
  useEffect(() => {
    const pathname = location.pathname;
    const findMenuByPath = (menus: MenuItem[]): MenuItem | null => {
      for (const menu of menus) {
        if (menu.path === pathname || `/${menu.path}` === pathname) {
          return menu;
        }
        if (menu.children) {
          const found = findMenuByPath(menu.children);
          if (found) return found;
        }
      }
      return null;
    };

    const rootMenu = asyncRouters?.[0];
    if (rootMenu?.children) {
      const currentMenu = findMenuByPath(rootMenu.children);
      if (currentMenu) {
        setSelectedKeys([currentMenu.name]);
      }
    }
  }, [location.pathname, asyncRouters]);

  // Handle menu click
  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    const menuItem = routeMap?.[key];
    if (!menuItem) {
      history.push(`/${key}`);
      return;
    }

    if (key.startsWith('http://') || key.startsWith('https://')) {
      window.open(key, '_blank');
      return;
    }

    const query: Record<string, string> = {};
    const params: Record<string, string> = {};
    menuItem.parameters?.forEach((param: any) => {
      if (param.type === 'query') {
        query[param.key] = param.value;
      } else {
        params[param.key] = param.value;
      }
    });

    history.push({
      pathname: menuItem.path?.startsWith('/') ? menuItem.path : `/${menuItem.path}`,
      query,
    });
  };

  return (
    <div
      style={{
        flex: 1,
        overflow: 'auto',
        display: 'flex',
        alignItems: 'center',
      }}
    >
      <Menu
        theme={theme}
        mode="horizontal"
        selectedKeys={selectedKeys}
        onClick={handleMenuClick}
        items={menuItems}
        style={{
          flex: 1,
          border: 'none',
          backgroundColor: 'transparent',
          lineHeight: '62px',
        }}
      />
    </div>
  );
};

export default HeadMode;
