/**
 * KRA - Command Menu Component
 * 快捷搜索菜单，支持Ctrl+K快捷键
 */
import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Input, List, Typography, Space, Tag } from 'antd';
import { SearchOutlined, ArrowRightOutlined, BulbOutlined, LogoutOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { createStyles } from 'antd-style';

const { Text } = Typography;

const useStyles = createStyles(({ token }) => ({
  searchInput: {
    fontSize: 16,
    padding: '12px 16px',
  },
  categoryTitle: {
    fontSize: 12,
    fontWeight: 600,
    color: token.colorTextSecondary,
    marginTop: 8,
    marginBottom: 4,
  },
  listItem: {
    padding: '8px 12px',
    cursor: 'pointer',
    borderRadius: 4,
    '&:hover': {
      backgroundColor: token.colorBgTextHover,
    },
  },
}));

interface CommandMenuProps {
  open: boolean;
  onClose: () => void;
}

interface MenuItem {
  label: string;
  path?: string;
  action?: () => void;
  icon?: React.ReactNode;
}

interface MenuCategory {
  label: string;
  items: MenuItem[];
}

const CommandMenu: React.FC<CommandMenuProps> = ({ open, onClose }) => {
  const { styles } = useStyles();
  const [searchValue, setSearchValue] = useState('');
  const { initialState, setInitialState } = useModel('@@initialState');

  // 菜单项
  const menuCategories: MenuCategory[] = useMemo(() => {
    const categories: MenuCategory[] = [
      {
        label: '跳转',
        items: [
          { label: '仪表盘', path: '/dashboard' },
          { label: '用户管理', path: '/admin/user' },
          { label: '角色管理', path: '/admin/authority' },
          { label: '菜单管理', path: '/admin/menu' },
          { label: 'API管理', path: '/admin/api' },
          { label: '操作日志', path: '/admin/operation' },
          { label: '字典管理', path: '/admin/dictionary' },
          { label: '参数配置', path: '/admin/params' },
          { label: '系统配置', path: '/systemTools/system' },
          { label: '个人信息', path: '/person' },
          { label: '关于', path: '/about' },
        ],
      },
      {
        label: '操作',
        items: [
          {
            label: '亮色主题',
            icon: <BulbOutlined />,
            action: () => {
              setInitialState((s) => ({
                ...s,
                settings: { ...s?.settings, navTheme: 'light' },
              }));
            },
          },
          {
            label: '暗色主题',
            icon: <BulbOutlined />,
            action: () => {
              setInitialState((s) => ({
                ...s,
                settings: { ...s?.settings, navTheme: 'realDark' },
              }));
            },
          },
          {
            label: '退出登录',
            icon: <LogoutOutlined />,
            action: () => {
              history.push('/user/login');
            },
          },
        ],
      },
    ];
    return categories;
  }, [setInitialState]);

  // 过滤菜单
  const filteredCategories = useMemo(() => {
    if (!searchValue) return menuCategories;
    return menuCategories
      .map((category) => ({
        ...category,
        items: category.items.filter((item) =>
          item.label.toLowerCase().includes(searchValue.toLowerCase())
        ),
      }))
      .filter((category) => category.items.length > 0);
  }, [menuCategories, searchValue]);

  // 处理点击
  const handleItemClick = (item: MenuItem) => {
    if (item.path) {
      history.push(item.path);
    } else if (item.action) {
      item.action();
    }
    onClose();
    setSearchValue('');
  };

  // 监听Ctrl+K快捷键
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.ctrlKey && e.key === 'k') {
        e.preventDefault();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  return (
    <Modal
      open={open}
      onCancel={onClose}
      footer={null}
      width={500}
      closable={false}
      styles={{ body: { maxHeight: '50vh', overflow: 'auto', padding: '12px' } }}
    >
      <Input
        placeholder="请输入你需要快捷到达的功能"
        prefix={<SearchOutlined />}
        value={searchValue}
        onChange={(e) => setSearchValue(e.target.value)}
        className={styles.searchInput}
        autoFocus
        allowClear
      />
      {filteredCategories.map((category, index) => (
        <div key={index}>
          {category.items.length > 0 && (
            <>
              <div className={styles.categoryTitle}>{category.label}</div>
              <List
                size="small"
                dataSource={category.items}
                renderItem={(item) => (
                  <div
                    className={styles.listItem}
                    onClick={() => handleItemClick(item)}
                  >
                    <Space>
                      {item.icon || <ArrowRightOutlined />}
                      <Text>{item.label}</Text>
                    </Space>
                  </div>
                )}
              />
            </>
          )}
        </div>
      ))}
    </Modal>
  );
};

export default CommandMenu;
