/**
 * KRA - Global Search Component
 * Command palette style search for quick navigation
 */
import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { Modal, Input, List, Empty, Tag } from 'antd';
import { SearchOutlined, FileOutlined, SettingOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { useAsyncRouters } from '@/models';
import * as Icons from '@ant-design/icons';

interface SearchItem {
  key: string;
  title: string;
  path: string;
  icon?: string;
  type: 'menu' | 'action';
  parent?: string;
}

interface SearchProps {
  /** Whether the search modal is visible */
  visible: boolean;
  /** Callback when modal closes */
  onClose: () => void;
}

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

const Search: React.FC<SearchProps> = ({ visible, onClose }) => {
  const asyncRouters = useAsyncRouters();
  const [keyword, setKeyword] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(0);
  const inputRef = useRef<any>(null);

  // Flatten menu items for search
  const searchItems = useMemo(() => {
    const items: SearchItem[] = [];
    
    const flattenMenus = (menus: any[], parent?: string) => {
      menus?.forEach((menu) => {
        if (menu.hidden) return;
        
        items.push({
          key: menu.name,
          title: menu.meta?.title || menu.name,
          path: menu.path?.startsWith('/') ? menu.path : `/${menu.path}`,
          icon: menu.meta?.icon,
          type: 'menu',
          parent,
        });
        
        if (menu.children?.length > 0) {
          flattenMenus(menu.children, menu.meta?.title || menu.name);
        }
      });
    };
    
    const rootMenu = asyncRouters?.[0];
    if (rootMenu?.children) {
      flattenMenus(rootMenu.children);
    }
    
    // Add some common actions
    items.push(
      { key: 'action-profile', title: '个人中心', path: '/person', icon: 'UserOutlined', type: 'action' },
      { key: 'action-settings', title: '系统设置', path: '/system/config', icon: 'SettingOutlined', type: 'action' },
    );
    
    return items;
  }, [asyncRouters]);

  // Filter items based on keyword
  const filteredItems = useMemo(() => {
    if (!keyword.trim()) {
      return searchItems.slice(0, 10);
    }
    
    const lowerKeyword = keyword.toLowerCase();
    return searchItems.filter((item) => {
      return (
        item.title.toLowerCase().includes(lowerKeyword) ||
        item.path.toLowerCase().includes(lowerKeyword) ||
        item.parent?.toLowerCase().includes(lowerKeyword)
      );
    }).slice(0, 20);
  }, [searchItems, keyword]);

  // Reset state when modal opens
  useEffect(() => {
    if (visible) {
      setKeyword('');
      setSelectedIndex(0);
      setTimeout(() => {
        inputRef.current?.focus();
      }, 100);
    }
  }, [visible]);

  // Handle keyboard navigation
  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        setSelectedIndex((prev) => Math.min(prev + 1, filteredItems.length - 1));
        break;
      case 'ArrowUp':
        e.preventDefault();
        setSelectedIndex((prev) => Math.max(prev - 1, 0));
        break;
      case 'Enter':
        e.preventDefault();
        if (filteredItems[selectedIndex]) {
          handleSelect(filteredItems[selectedIndex]);
        }
        break;
      case 'Escape':
        onClose();
        break;
    }
  }, [filteredItems, selectedIndex, onClose]);

  // Handle item selection
  const handleSelect = (item: SearchItem) => {
    history.push(item.path);
    onClose();
  };

  return (
    <Modal
      open={visible}
      onCancel={onClose}
      footer={null}
      closable={false}
      width={600}
      centered
      styles={{
        body: { padding: 0 },
      }}
      style={{ top: 100 }}
    >
      <div style={{ padding: '12px 16px', borderBottom: '1px solid #f0f0f0' }}>
        <Input
          ref={inputRef}
          prefix={<SearchOutlined style={{ color: '#999' }} />}
          placeholder="搜索菜单或功能..."
          value={keyword}
          onChange={(e) => {
            setKeyword(e.target.value);
            setSelectedIndex(0);
          }}
          onKeyDown={handleKeyDown}
          bordered={false}
          size="large"
          style={{ fontSize: 16 }}
        />
      </div>
      
      <div style={{ maxHeight: 400, overflow: 'auto' }}>
        {filteredItems.length > 0 ? (
          <List
            dataSource={filteredItems}
            renderItem={(item, index) => (
              <List.Item
                onClick={() => handleSelect(item)}
                style={{
                  padding: '12px 16px',
                  cursor: 'pointer',
                  backgroundColor: index === selectedIndex ? '#f5f5f5' : 'transparent',
                }}
                onMouseEnter={() => setSelectedIndex(index)}
              >
                <List.Item.Meta
                  avatar={getIcon(item.icon)}
                  title={
                    <span>
                      {item.title}
                      {item.parent && (
                        <Tag color="blue" style={{ marginLeft: 8, fontSize: 12 }}>
                          {item.parent}
                        </Tag>
                      )}
                    </span>
                  }
                  description={
                    <span style={{ color: '#999', fontSize: 12 }}>
                      {item.path}
                    </span>
                  }
                />
              </List.Item>
            )}
          />
        ) : (
          <Empty
            description="未找到匹配的菜单或功能"
            style={{ padding: '40px 0' }}
          />
        )}
      </div>
      
      <div
        style={{
          padding: '8px 16px',
          borderTop: '1px solid #f0f0f0',
          display: 'flex',
          justifyContent: 'space-between',
          color: '#999',
          fontSize: 12,
        }}
      >
        <span>
          <kbd style={{ padding: '2px 6px', backgroundColor: '#f5f5f5', borderRadius: 4, marginRight: 4 }}>↑</kbd>
          <kbd style={{ padding: '2px 6px', backgroundColor: '#f5f5f5', borderRadius: 4, marginRight: 8 }}>↓</kbd>
          导航
        </span>
        <span>
          <kbd style={{ padding: '2px 6px', backgroundColor: '#f5f5f5', borderRadius: 4, marginRight: 4 }}>Enter</kbd>
          选择
        </span>
        <span>
          <kbd style={{ padding: '2px 6px', backgroundColor: '#f5f5f5', borderRadius: 4, marginRight: 4 }}>Esc</kbd>
          关闭
        </span>
      </div>
    </Modal>
  );
};

export default Search;
