import React, { useState, useEffect, useRef, useMemo } from 'react';
import { 
  Search, Plus, RefreshCw, Edit2, Trash2,
  FileText, Folder, Menu, Settings, User, Users, 
  Lock, Unlock, Edit, Minus, 
  CheckCircle, X, AlertTriangle, Info, Bell, MessageSquare, 
  Phone, MapPin, Calendar, Clock, Star, Share2, 
  Download, Upload, Eye, EyeOff, Home, 
  ShoppingBag, Package, Database, PieChart, BarChart3, 
  Grid3x3, List, Link2, Key, Wrench, Monitor, Server
} from 'lucide-react';
import { Modal, Button, Input, Space, Table as AntdTable, Switch as AntdSwitch } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { menuApi, MenuVO, MenuQueryParams, MenuType } from '../api/Menu';
import { handleTree, TreeNode } from '../utils/tree';
import { toast } from 'sonner';
import { DICT_TYPE, getDictLabel } from '../utils/dict';
import { Button as UIButton } from './ui/button';
import MenuForm, { MenuFormRef } from './MenuForm';
import './IsolationWorkListTable.css';
import PermissionWrapper from './PermissionWrapper';
import { useTranslation } from 'react-i18next';

interface MenuNode extends MenuVO {
  children?: MenuNode[];
  key?: number;
}

export default function MenuManagement() {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<MenuVO[]>([]);
  const [treeList, setTreeList] = useState<MenuNode[]>([]);
  const [queryParams, setQueryParams] = useState<MenuQueryParams>({
    name: undefined,
    status: undefined,
  });
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);
  const [isExpandAll, setIsExpandAll] = useState(false);
  const [menuStatusUpdating, setMenuStatusUpdating] = useState<Record<number, boolean>>({});
  const formRef = useRef<MenuFormRef>(null);

  // 获取菜单列表
  const getList = async (params?: MenuQueryParams) => {
    const currentParams = params || queryParams;
    setLoading(true);
    try {
      const response = await menuApi.getMenuList(currentParams);
      const data = Array.isArray(response) ? response : (response?.data || response || []);
      setList(data);
      // 过滤掉没有 id 的数据，然后转换为树形结构
      const validData = data.filter(item => item.id !== undefined && item.id !== null);
      const treeData = handleTree(validData as any) as MenuNode[];
      // 为每个节点添加 key 属性（Ant Design Table 需要）
      const addKeys = (nodes: MenuNode[]): MenuNode[] => {
        return nodes.map(node => ({
          ...node,
          key: node.id,
          children: node.children ? addKeys(node.children) : undefined,
        }));
      };
      const treeDataWithKeys = addKeys(treeData);
      setTreeList(treeDataWithKeys);
      
      // 默认折叠，不展开任何节点
      setExpandedRowKeys([]);
      setIsExpandAll(false);
    } catch (error: any) {
      toast.error(error.message || '获取菜单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取所有菜单ID（递归）
  const getAllMenuIds = (nodes: MenuNode[]): React.Key[] => {
    const ids: React.Key[] = [];
    nodes.forEach(node => {
      if (node.id) {
        ids.push(node.id);
        if (node.children && node.children.length > 0) {
          ids.push(...getAllMenuIds(node.children));
        }
      }
    });
    return ids;
  };

  useEffect(() => {
    getList();
  }, []);

  // 搜索
  const handleQuery = () => {
    getList();
  };

  // 重置搜索
  const resetQuery = () => {
    const resetParams: MenuQueryParams = {
      name: undefined,
      status: undefined,
    };
    // 先设置状态，确保搜索框能同步更新
    setQueryParams(resetParams);
    // 立即使用重置后的参数获取列表
    getList(resetParams);
  };

  // 展开/折叠所有
  const toggleExpandAll = () => {
    if (isExpandAll) {
      setExpandedRowKeys([]);
      setIsExpandAll(false);
    } else {
      const allIds = getAllMenuIds(treeList);
      setExpandedRowKeys(allIds);
      setIsExpandAll(true);
    }
  };

  // 打开表单
  const openForm = (type: string, id?: number, parentId?: number) => {
    if (formRef.current) {
      formRef.current.open(type, id, parentId);
    }
  };

  // 删除菜单
  const handleDelete = async (id: number, name: string) => {
    Modal.confirm({
      title: t('common.confirmDelete'),
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>
            {t('common.confirmDeleteText')}{' '}
            <strong>"{name}"</strong>?
          </p>
          <p style={{ color: '#ff4d4f', marginTop: '8px' }}>
            {t('common.confirmDeleteWarning')}
          </p>
        </div>
      ),
      okText: t('common.confirm'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          await menuApi.deleteMenu(id);
          toast.success(t('common.deleteSuccess'));
          await getList();
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 状态切换
  const handleStatusChanged = async (menu: MenuVO, val: number) => {
    if (!menu.id) {
      toast.error(t('common.error'));
      return;
    }

    setMenuStatusUpdating(prev => ({ ...prev, [menu.id!]: true }));
    try {
      // 确保传递完整的菜单数据，包括所有必需字段
      const updatedMenu: MenuVO = {
        id: menu.id,
        name: menu.name,
        permission: menu.permission ?? '',
        type: menu.type,
        sort: menu.sort ?? 0,
        parentId: menu.parentId ?? 0,
        path: menu.path ?? '',
        icon: menu.icon ?? '',
        component: menu.component ?? undefined,
        componentName: menu.componentName ?? undefined,
        status: val,
        visible: menu.visible ?? true,
        keepAlive: menu.keepAlive ?? true,
        alwaysShow: menu.alwaysShow ?? true,
        createTime: menu.createTime,
      };
      await menuApi.updateMenu(updatedMenu);
      toast.success(t('common.updateSuccess'));
      await getList();
    } catch (error: any) {
      toast.error(error.message || t('common.updateFailed'));
      // 恢复原状态 - 重新获取列表以恢复正确的状态
      await getList();
    } finally {
      setMenuStatusUpdating(prev => ({ ...prev, [menu.id!]: false }));
    }
  };

  // 刷新菜单缓存
  const refreshMenu = async () => {
    if (!confirm('即将更新缓存并刷新浏览器！')) {
      return;
    }

    try {
      // 清空缓存
      localStorage.removeItem('token');
      localStorage.removeItem('permissionInfo');
      localStorage.removeItem('roleRouters');
      
      // 刷新浏览器
      window.location.reload();
    } catch (error) {
      console.error('刷新失败:', error);
    }
  };

  // ElementPlus 图标名称到 React 图标的映射
  const iconMap: Record<string, React.ComponentType<any>> = {
    'ep:document': FileText,
    'ep:folder': Folder,
    'ep:menu': Menu,
    'ep:setting': Settings,
    'ep:user': User,
    'ep:users': Users,
    'ep:lock': Lock,
    'ep:unlock': Unlock,
    'ep:search': Search,
    'ep:edit': Edit,
    'ep:delete': Trash2,
    'ep:plus': Plus,
    'ep:minus': Minus,
    'ep:check': CheckCircle,
    'ep:close': X,
    'ep:warning': AlertTriangle,
    'ep:info': Info,
    'ep:success': CheckCircle,
    'ep:error': X,
    'ep:bell': Bell,
    'ep:message': MessageSquare,
    'ep:phone': Phone,
    'ep:location': MapPin,
    'ep:calendar': Calendar,
    'ep:clock': Clock,
    'ep:star': Star,
    'ep:share': Share2,
    'ep:download': Download,
    'ep:upload': Upload,
    'ep:refresh': RefreshCw,
    'ep:view': Eye,
    'ep:hide': EyeOff,
    'ep:home': Home,
    'ep:shop': ShoppingBag,
    'ep:goods': Package,
    'ep:data': Database,
    'ep:pie-chart': PieChart,
    'ep:bar-chart': BarChart3,
    'ep:grid': Grid3x3,
    'ep:list': List,
    'ep:connection': Link2,
    'ep:link': Link2,
    'ep:key': Key,
    'ep:tools': Wrench,
    'ep:monitor': Monitor,
    'ep:server': Server,
    'ep:database': Database,
  };

  // 可用图标池（用于随机分配）
  const iconPool = [
    FileText, Folder, Menu, Settings, User, Users,
    Lock, Unlock, Search, Edit, Trash2, Plus, Minus,
    CheckCircle, X, AlertTriangle, Info, Bell, MessageSquare,
    Phone, MapPin, Calendar, Clock, Star, Share2,
    Download, Upload, RefreshCw, Eye, EyeOff, Home,
    ShoppingBag, Package, Database, PieChart, BarChart3,
    Grid3x3, List, Link2, Key, Wrench, Monitor, Server
  ];

  // 根据字符串生成哈希值（用于稳定随机分配）
  const hashString = (str: string): number => {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash; // Convert to 32bit integer
    }
    return Math.abs(hash);
  };

  // 获取图标组件
  const getIconComponent = (iconName?: string, menuName?: string, menuId?: number) => {
    // 首先尝试从 ElementPlus 映射中获取
    if (iconName && iconMap[iconName]) {
      return iconMap[iconName];
    }
    
    // 如果没有映射，根据菜单名称或ID随机分配一个图标
    const seed = menuName || menuId?.toString() || 'default';
    const hash = hashString(seed);
    const randomIndex = hash % iconPool.length;
    return iconPool[randomIndex];
  };

  // 获取菜单类型标签
  const getMenuTypeLabel = (type: number) => {
    switch (type) {
      case MenuType.DIR:
        return '目录';
      case MenuType.MENU:
        return '菜单';
      case MenuType.BUTTON:
        return '按钮';
      default:
        return '未知';
    }
  };

  // 表格列定义
  const columns: ColumnsType<MenuNode> = useMemo(() => [
    {
      title: t('table.menuName'),
      dataIndex: 'name',
      key: 'name',
      width: 250,
      align: 'center',
      render: (text: string, record: MenuNode) => {
        const IconComponent = getIconComponent(record.icon, record.name, record.id);
    return (
            <div className="flex items-center gap-1.5 justify-center">
              <IconComponent className="w-4 h-4 text-gray-500" />
            <span>{text}</span>
            </div>
        );
      },
    },
    {
      title: t('table.icon'),
      dataIndex: 'icon',
      key: 'icon',
      width: 100,
      align: 'center',
      render: (_: any, record: MenuNode) => {
        const IconComponent = getIconComponent(record.icon, record.name, record.id);
        return (
            <div className="flex items-center justify-center">
              <IconComponent className="w-4 h-4" />
            </div>
        );
      },
    },
    {
      title: t('table.sort'),
      dataIndex: 'sort',
      key: 'sort',
      width: 60,
      align: 'center',
    },
    {
      title: t('table.permission'),
      dataIndex: 'permission',
      key: 'permission',
      width: 300,
      align: 'center',
      ellipsis: true,
      render: (text: string, record: MenuNode) => {
        const permission = record.permission;
        return permission ? String(permission) : '-';
      },
    },
    {
      title: t('table.componentPath'),
      dataIndex: 'component',
      key: 'component',
      width: 500,
      align: 'center',
      ellipsis: true,
      render: (text: string, record: MenuNode) => {
        const component = record.component;
        return component ? String(component) : '-';
      },
    },
    {
      title: t('table.componentName'),
      dataIndex: 'componentName',
      key: 'componentName',
      width: 200,
      align: 'center',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: t('table.status'),
      dataIndex: 'status',
      key: 'status',
      width: 60,
      align: 'center',
      render: (_: any, record: MenuNode) => {
        const isChecked = Number(record.status) === 0;
        return (
          <div className="flex items-center justify-center">
            <AntdSwitch
              checked={isChecked}
              onChange={(checked) => {
                if (!menuStatusUpdating[record.id!]) {
                  const newStatus = checked ? 0 : 1;
                  handleStatusChanged(record, newStatus);
                }
              }}
              disabled={menuStatusUpdating[record.id!]}
              loading={menuStatusUpdating[record.id!]}
              style={{
                ...(isChecked ? { 
                  backgroundColor: '#52c41a',
                } : {})
              }}
              className={isChecked ? 'ant-switch-checked-green' : ''}
            />
          </div>
        );
      },
    },
    {
      title: t('table.operation'),
      key: 'action',
      width: 240,
      align: 'center',
      fixed: 'right',
      render: (_: any, record: MenuNode) => (
            <div className="flex items-center gap-2 justify-center">
              <PermissionWrapper permission="system:menu:update">
                <UIButton
                  variant="ghost"
                  size="sm"
              onClick={() => openForm('update', record.id)}
                  className="h-8 px-2 transition-colors hover:underline"
                  style={{ color: '#000000' }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.color = '#1677ff';
                    e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.color = '#000000';
                    e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
                  }}
                >
                  <Edit2 className="w-4 h-4" style={{ color: '#000000' }} />
                  <span className="ml-1">{t('common.edit')}</span>
                </UIButton>
              </PermissionWrapper>
              <PermissionWrapper permission="system:menu:create">
                <UIButton
                  variant="ghost"
                  size="sm"
              onClick={() => openForm('create', undefined, record.id)}
                  className="h-8 px-2 transition-colors hover:underline"
                  style={{ color: '#000000' }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.color = '#1677ff';
                    e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.color = '#000000';
                    e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
                  }}
                >
                  <Plus className="w-4 h-4" style={{ color: '#000000' }} />
                  <span className="ml-1">{t('common.addNew')}</span>
                </UIButton>
              </PermissionWrapper>
              <PermissionWrapper permission="system:menu:delete">
                <UIButton
                  variant="ghost"
                  size="sm"
              onClick={() => handleDelete(record.id!, record.name)}
                  className="h-8 px-2 transition-colors hover:underline"
                  style={{ color: '#000000' }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.color = '#1677ff';
                    e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.color = '#000000';
                    e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
                  }}
                >
                  <Trash2 className="w-4 h-4" style={{ color: '#000000' }} />
                  <span className="ml-1">{t('common.delete')}</span>
                </UIButton>
              </PermissionWrapper>
            </div>
      ),
    },
  ], [menuStatusUpdating, t]);

  return (
    <>
      <style>{`
        .ant-switch-checked-green.ant-switch-checked {
          background-color: #52c41a !important;
        }
        /* 调整菜单管理表格中展开图标和内容之间的间距 */
        .ant-table-tbody > tr > td:first-child {
          padding-left: 8px !important;
        }
        .ant-table-row-expand-icon-cell {
          padding-right: 4px !important;
        }
        .ant-table-row-expand-icon {
          margin-right: 0 !important;
        }
      `}</style>
      <div className="space-y-4">
        {/* 搜索栏 */}
      <div className="bg-white rounded-xl border border-gray-200/50 shadow-sm p-4 lg:p-5">
        <div className="flex items-center justify-between gap-3 lg:gap-4 flex-wrap min-w-0">
          {/* 搜索条件 + 搜索、重置紧跟其后 */}
          <div className="flex items-center gap-2 lg:gap-3 flex-wrap min-w-0">
            <div className="flex items-center gap-2 lg:gap-3 w-[200px] min-w-[100px] flex-shrink">
              <label className="text-sm font-medium text-gray-700 whitespace-nowrap flex-shrink-0">{t('form.menuName')}：</label>
              <Input
                value={queryParams.name || ''}
                onChange={(e) => setQueryParams(prev => ({ ...prev, name: e.target.value }))}
                onPressEnter={handleQuery}
                placeholder={t('form.menuNamePlaceholder')}
                className="min-w-0 w-full"
                allowClear
              />
            </div>
            <Space className="flex-shrink-0" size="small">
              <PermissionWrapper permission="system:menu:query">
                <Button
                  type="primary"
                  icon={<Search className="w-4 h-4" />}
                  onClick={handleQuery}
                >
                  {t('common.search')}
                </Button>
              </PermissionWrapper>
              <PermissionWrapper permission="system:menu:query">
                <Button
                  icon={<RefreshCw className="w-4 h-4" />}
                  onClick={resetQuery}
                >
                  {t('common.reset')}
                </Button>
              </PermissionWrapper>
            </Space>
          </div>
          {/* 新增、展开/收起、刷新缓存等按钮留在最右侧 */}
          <Space className="flex-shrink-0" size="small">
            <PermissionWrapper permission="system:menu:create">
              <Button
                type="primary"
                icon={<Plus className="w-4 h-4" />}
                onClick={() => openForm('create')}
              >
                {t('common.addNew')}
              </Button>
            </PermissionWrapper>
            <Button
              onClick={toggleExpandAll}
            >
              {isExpandAll ? t('common.collapseAll') : t('common.expandAll')}
            </Button>
            <Button
              icon={<RefreshCw className="w-4 h-4" />}
              onClick={refreshMenu}
            >
              {t('common.refreshCache')}
            </Button>
          </Space>
        </div>
      </div>

      {/* 表格 */}
      <div className="isolation-work-list-table bg-white rounded-lg border border-gray-200 overflow-hidden">
        <AntdTable<MenuNode>
          columns={columns}
          dataSource={treeList}
          loading={loading}
          rowKey="id"
          pagination={false}
          expandable={{
            expandedRowKeys,
            onExpandedRowsChange: (keys) => setExpandedRowKeys(keys as React.Key[]),
            indentSize: 24,
            defaultExpandAllRows: false,
          }}
          scroll={{ x: 'max-content' }}
          size="middle"
          rowClassName={(_, index) =>
            index !== undefined && index % 2 === 1 ? 'isolation-work-list-row-alt' : ''
          }
        />
      </div>

        {/* 表单弹窗 */}
        <MenuForm ref={formRef} onSuccess={getList} />
      </div>
    </>
  );
}
