/**
 * KRA - Menu Permission Component
 * Configure menu permissions for authority/role
 */
import React, { useState, useEffect } from 'react';
import { Tree, Input, Button, message, Modal, Table, Space } from 'antd';
import type { DataNode, TreeProps } from 'antd/es/tree';
import {
  getBaseMenuTree,
  getMenuAuthority,
  addMenuAuthority,
} from '@/services/kratos/menu';
import { updateAuthority } from '@/services/kratos/authority';
import { getAuthorityBtn, setAuthorityBtn } from '@/services/kratos/authorityBtn';

const { Search } = Input;

interface Authority {
  authorityId: string;
  authorityName: string;
  parentId: string;
  defaultRouter?: string;
}

interface MenuItem {
  ID: number;
  parentId: number;
  name: string;
  path: string;
  meta: {
    title: string;
    icon?: string;
  };
  children?: MenuItem[];
  menuBtn?: Array<{ ID: number; name: string; desc: string }>;
}

interface MenuPermissionProps {
  row: Authority;
  onChangeRow: (key: string, value: any) => void;
}

const MenuPermission: React.FC<MenuPermissionProps> = ({ row, onChangeRow }) => {
  const [menuTreeData, setMenuTreeData] = useState<DataNode[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [filterText, setFilterText] = useState('');
  const [loading, setLoading] = useState(false);
  const [menuMap, setMenuMap] = useState<Map<number, MenuItem>>(new Map());

  // 按钮权限弹窗
  const [btnModalVisible, setBtnModalVisible] = useState(false);
  const [btnData, setBtnData] = useState<Array<{ ID: number; name: string; desc: string }>>([]);
  const [selectedBtnKeys, setSelectedBtnKeys] = useState<React.Key[]>([]);
  const [currentMenuId, setCurrentMenuId] = useState<number>(0);

  useEffect(() => {
    fetchMenuData();
  }, [row.authorityId]);

  const fetchMenuData = async () => {
    setLoading(true);
    try {
      // 获取所有菜单树
      const treeRes = await getBaseMenuTree();
      const menus = treeRes.data?.menus || [];
      
      // 构建菜单映射
      const map = new Map<number, MenuItem>();
      const buildMap = (items: MenuItem[]) => {
        items.forEach((item) => {
          map.set(item.ID, item);
          if (item.children) buildMap(item.children);
        });
      };
      buildMap(menus);
      setMenuMap(map);

      // 转换为 Tree 数据格式
      const treeData = convertToTreeData(menus);
      setMenuTreeData(treeData);
      
      // 展开所有节点
      const allKeys = getAllKeys(menus);
      setExpandedKeys(allKeys);

      // 获取当前角色的菜单权限
      const authRes = await getMenuAuthority({ authorityId: row.authorityId });
      const authorizedMenus = authRes.data?.menus || [];
      
      // 只选中叶子节点，防止全选父级
      const checkedIds: React.Key[] = [];
      authorizedMenus.forEach((menu: any) => {
        const menuId = menu.menuId || menu.ID;
        // 检查是否有子菜单被选中
        const hasSelectedChild = authorizedMenus.some(
          (m: any) => (m.parentId || 0) === menuId
        );
        if (!hasSelectedChild) {
          checkedIds.push(menuId);
        }
      });
      setCheckedKeys(checkedIds);
    } catch (error) {
      console.error('Failed to fetch menu data:', error);
    } finally {
      setLoading(false);
    }
  };

  // 转换菜单数据为 Tree 格式
  const convertToTreeData = (menus: MenuItem[]): DataNode[] => {
    return menus.map((menu) => ({
      key: menu.ID,
      title: (
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span>{menu.meta?.title || menu.name}</span>
          {checkedKeys.includes(menu.ID) && 
           !menu.name?.startsWith('http://') && 
           !menu.name?.startsWith('https://') && (
            <Button
              type="link"
              size="small"
              style={{ color: row.defaultRouter === menu.name ? '#E6A23C' : '#85ce61' }}
              onClick={(e) => {
                e.stopPropagation();
                handleSetDefault(menu);
              }}
            >
              {row.defaultRouter === menu.name ? '首页' : '设为首页'}
            </Button>
          )}
          {menu.menuBtn && menu.menuBtn.length > 0 && (
            <Button
              type="link"
              size="small"
              onClick={(e) => {
                e.stopPropagation();
                handleOpenBtnModal(menu);
              }}
            >
              分配按钮
            </Button>
          )}
        </span>
      ),
      children: menu.children ? convertToTreeData(menu.children) : undefined,
      disabled: row.defaultRouter === menu.name,
    }));
  };

  // 获取所有节点 key
  const getAllKeys = (menus: MenuItem[]): React.Key[] => {
    const keys: React.Key[] = [];
    const traverse = (items: MenuItem[]) => {
      items.forEach((item) => {
        keys.push(item.ID);
        if (item.children) traverse(item.children);
      });
    };
    traverse(menus);
    return keys;
  };

  // 设置默认首页
  const handleSetDefault = async (menu: MenuItem) => {
    try {
      const res = await updateAuthority({
        authorityId: row.authorityId,
        authorityName: row.authorityName,
        parentId: row.parentId,
        defaultRouter: menu.name,
      });
      if (res.code === 0) {
        onChangeRow('defaultRouter', res.data?.authority?.defaultRouter || menu.name);
        message.success('设置成功');
        // 重新加载以更新 UI
        fetchMenuData();
      }
    } catch (error) {
      message.error('设置失败');
    }
  };

  // 打开按钮权限弹窗
  const handleOpenBtnModal = async (menu: MenuItem) => {
    setCurrentMenuId(menu.ID);
    setBtnData(menu.menuBtn || []);
    
    try {
      const res = await getAuthorityBtn({
        menuID: menu.ID,
        authorityId: row.authorityId,
      });
      if (res.code === 0) {
        setSelectedBtnKeys(res.data?.selected || []);
      }
    } catch (error) {
      console.error('Failed to get authority btn:', error);
    }
    
    setBtnModalVisible(true);
  };

  // 确认按钮权限
  const handleConfirmBtn = async () => {
    try {
      const res = await setAuthorityBtn({
        menuID: currentMenuId,
        authorityId: row.authorityId,
        selected: selectedBtnKeys as string[],
      });
      if (res.code === 0) {
        message.success('设置成功');
        setBtnModalVisible(false);
      }
    } catch (error) {
      message.error('设置失败');
    }
  };

  // 确认菜单权限
  const handleConfirm = async () => {
    try {
      // 获取所有选中的节点（包括半选中的父节点）
      const allCheckedKeys = [...checkedKeys];
      
      const res = await addMenuAuthority({
        menus: allCheckedKeys as number[],
        authorityId: row.authorityId,
      });
      if (res.code === 0) {
        message.success('菜单设置成功');
      }
    } catch (error) {
      message.error('设置失败');
    }
  };

  // 处理选中变化
  const handleCheck: TreeProps['onCheck'] = (checked, info) => {
    setCheckedKeys(checked as React.Key[]);
  };

  // 过滤节点
  const filterTreeNode = (node: DataNode): boolean => {
    if (!filterText) return true;
    const title = typeof node.title === 'string' ? node.title : '';
    return title.toLowerCase().includes(filterText.toLowerCase());
  };

  // 按钮表格列
  const btnColumns = [
    { title: '按钮名称', dataIndex: 'name', key: 'name' },
    { title: '按钮备注', dataIndex: 'desc', key: 'desc' },
  ];

  return (
    <div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, position: 'sticky', top: 0, background: '#fff', zIndex: 10, padding: '8px 0' }}>
        <Search
          placeholder="筛选菜单"
          value={filterText}
          onChange={(e) => setFilterText(e.target.value)}
          style={{ flex: 1 }}
        />
        <Button type="primary" onClick={handleConfirm}>
          确定
        </Button>
      </div>
      <div style={{ maxHeight: 'calc(100vh - 300px)', overflow: 'auto' }}>
        <Tree
          checkable
          defaultExpandAll
          expandedKeys={expandedKeys}
          onExpand={setExpandedKeys}
          checkedKeys={checkedKeys}
          onCheck={handleCheck}
          treeData={menuTreeData}
          filterTreeNode={filterTreeNode}
        />
      </div>

      {/* 按钮权限弹窗 */}
      <Modal
        title="分配按钮"
        open={btnModalVisible}
        onCancel={() => setBtnModalVisible(false)}
        onOk={handleConfirmBtn}
        destroyOnClose
      >
        <Table
          rowKey="ID"
          columns={btnColumns}
          dataSource={btnData}
          pagination={false}
          rowSelection={{
            selectedRowKeys: selectedBtnKeys,
            onChange: (keys) => setSelectedBtnKeys(keys),
          }}
        />
      </Modal>
    </div>
  );
};

export default MenuPermission;
